1

How to add dynamic attribute to an object, for example I use the following code to add index (index)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...

2
  • That should work, but you're not very clear about what you expect the result to be. Commented Jun 8, 2011 at 14:49
  • This has nothing to do with Javascript events or with jQuery. And, so far as I can tell, it does work. What's the problem? Commented Jun 8, 2011 at 14:49

4 Answers 4

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

0

May you can try using :

myObj[index+""]='my'+index;

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.