0

我试图改进我的 javascript 在这里遇到了一些死胡同。

var schemes = {
    "own" : {
        "creatures" : ["creature1","creature2","creature3","creature4"],
        "spells" : ["spell1","spell2","spell3","spell4"],
        "items" : ["item1","item2","item3","item4"]
    },
    "enemy" : {
        "creatures" : ["creature1","creature2","creature3","hidden"],
        "spells" : ["spell1","spell2","hidden","hidden"],
        "items" : ["item1","item2","item3","hidden"]
    }
};

这是我的阵列。

然后我尝试为每个(我从 php 知道)做一个,但似乎 javascript 认为方案是一个对象,因此无法做一个:

for (var i=0;i<schemes.length;i++) {
 //code 
}

我错过了什么?scheme.length 说未定义

4

3 回答 3

4

schemes确实是一个“对象”,因此没有.length.

您可以使用Object.keys(schemes)来获取键的数组,或者:

for (var key in schemes) {
    var el = schemes[key];
     ...
}
于 2012-11-21T11:26:24.293 回答
2

您错过了实际上schemes是一个对象而不是数组的事实。

考虑以下:

myobject = { 'a' : 1, 'b' : 2, 'c' : 3 } // this is an object

myarray = [ 1, 2, 3 ] // this is an array

你可以用这些变量做什么:

for (var key in myobject) {
    console.log(key + ": " + myobject[key]);
}

for (var i = 0; i < myarray.length; i++) {
    console.log('Value at index ' + i + ':' + myarray[i]);
} 
于 2012-11-21T11:26:13.497 回答
2

Schemes 是一个对象。我想你想让它成为一个对象数组。

var schemes = [{
    "own" : {
        "creatures" : ["creature1","creature2","creature3","creature4"],
        "spells" : ["spell1","spell2","spell3","spell4"],
        "items" : ["item1","item2","item3","item4"]
    },
    "enemy" : {
        "creatures" : ["creature1","creature2","creature3","hidden"],
        "spells" : ["spell1","spell2","hidden","hidden"],
        "items" : ["item1","item2","item3","hidden"]
    }
}];

然后,您可以按如下方式遍历数组:

for (var i=0;i<schemes.length;i++) {
  alert(schemes[i].creatures[1]); //alerts creature1 (2x)
}
于 2012-11-21T11:26:31.127 回答