How to add dynamic attribute to an Object in JavaScript?
How to add dynamic attribute to an object, for example I use the following code to add index (inde开发者_运维技巧x
)attribute to myObj
, index
is a variable.
var myObj={};
for(var index=0; index<10; index++){
myObj[index]='my'+index;
}
But it does not work...
If what you really want is for "myObj" to have properties like "my0", "my1", through "my10", then what you want is
for (var index = 0; index < 10; ++index)
myObj['my' + index] = something;
Instead of creating an object with {}, use [] since you are creating a simple array.
var myObj=[];
for(var index=0; index<10; index++){
myObj[index]='my'+index;
}
May you can try using :
myObj[index+""]='my'+index;
You can't use a number as a property name in JavaScript in the same way you use a string.
Using myObj[1] will return the property value you're looking for, but myObj.1 will not.
It would be best to use a string like @Pointy and @sudimail recommended.
精彩评论