views:

66

answers:

2

I'm trying something like this, but this example does not work.

jsObj = {};

for (var i = 1; i <= 10; i++) {
    jsObj{'key' + i} = 'example ' + 1;
}

What can I do to make a dynamic key like this?

Thanks, Ryan

+3  A: 

Square brackets:

jsObj['key' + i] = 'example' + 1;
Pointy
is that format considered an array, though?
Ryan
@Ryan- No. Object properties can be created and values accessed through `obj[prop]` a.k.a. subscript notation and `obj.prop` a.k.a. dot notation. Using subscript notation allows dynamic properties to be created. Think of an object like a hashtable; add a key/value pair to the hashtable is similar to adding a property/value to a JavaScript object.
Russ Cam
@Ryan: associative arrays in JavaScript aren't *really* arrays, they're objects with properties. If you're using index-based keys for associative arrays, you should just use an indexed array (ie, instead of `{"key1":"example1", "key2":"example2"}` you should use `["example1", "example2"]`. It's much easier when you come to iterate over the elements later.
Andy E
Using subscript notation is also used with arrays, by providing the numerical index. Do not get confused with associative arrays from other languages however; an object should be used where you might use an associative array in another language. see http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/ for more details.
Russ Cam
ok, thank you.So, subscript notation, even though in square brackets, will not be converted into an array, if I have declared the type to be an object then?
Ryan
@Ryan- No, an object won't be converted to an array object using subscript notation. The notation is used for both object property and array index getter/setters.
Russ Cam
Well, sort-of. Arrays *are* objects, in Javascript, but they're special in slightly weird ways. An array is an array because it was an array "at birth". Something that's not an array (like your `jsObj`) can't really turn into an array, or anything like that.
Pointy
A: 

Associative Arrays in JavaScript don't really work the same as they do in other languages. for each statements are complicated (because they enumerate inherited prototype properties). You could declare properties on an object/associative array as Pointy mentioned, but really for this sort of thing you should use an array with the push method:

jsArr = []; 

for (var i = 1; i <= 10; i++) { 
    jsArr.push('example ' + 1); 
} 

Just don't forget that indexed arrays are zero-based so the first element will be jsArr[0], not jsArr[1].

Andy E
OK, thank you very much everyone! I appreciate the explanations.
Ryan