最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Using numbers for names of javascript object elements - Stack Overflow

programmeradmin2浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论