Ali
Ali

Reputation: 267177

Using numbers for names of javascript object elements

Is the following code valid?

var i;
var objs={};
for (i=0; i <10; i++)
{
   objs.i=new FooObject();
}

alert(objs.4.someMethod());

If not, how should it be rewritten to accomplish what I want?

Upvotes: 3

Views: 2255

Answers (4)

Sampson
Sampson

Reputation: 268424

You cannot use numericals for variable names 1. If you want to reference an item by a numerical value, use an array 2. You can then access items by their key in the array. If you want to cycle through, you can use the for...in option 3. It won't matter if your keys are sequential and contiguous:

var x;
var myItems = new Array();
myItems[0] = "Foo";
myItems[9] = "Bar";
myItems[5] = "Fiz";

for (x in myItems) {
  alert(myItems[x]);
}

1 http://www.w3schools.com/js/js_variables.asp
2 http://www.w3schools.com/js/js_obj_array.asp
3 http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_for_in

Upvotes: 2

Sinan Taifour
Sinan Taifour

Reputation: 10805

You should edit your code as following:

var i;
var objs = {};
for (i = 0; i < 10; i++) {
  objs[i] = new FooObject();
}

alert(objs[4].someMethod());

Upvotes: 4

Ryan McGrath
Ryan McGrath

Reputation: 2042

You can't use numbers as variable names, because straight up numbers exist as their own object set in Javascript (i.e, you could think of 4 as already being a global variable that you can't override).

Upvotes: 1

kemiller2002
kemiller2002

Reputation: 115518

var i; 
var objs = new Array();

for(i = 0; i < 10; i++)
{
   objs.push(new FooObject());
}


objs[4].someMethod();

Upvotes: 2

Related Questions