admin管理员组

文章数量:1332345

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 acplish what I want?

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 acplish what I want?

Share Improve this question asked Jul 20, 2009 at 17:13 AliAli 267k268 gold badges591 silver badges785 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

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());
var i; 
var objs = new Array();

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


objs[4].someMethod();

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./js/js_variables.asp
2 http://www.w3schools./js/js_obj_array.asp
3 http://www.w3schools./js/tryit.asp?filename=tryjs_array_for_in

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).

本文标签: jqueryUsing numbers for names of javascript object elementsStack Overflow