javascript数组基础知识

时间:2012-11-21 11:24:47

标签: javascript arrays

我试图改善我的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 
}

我错过了什么? schemes.length表示undefined

3 个答案:

答案 0 :(得分:4)

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

您可以使用Object.keys(schemes)获取密钥数组,或者:

for (var key in schemes) {
    var el = schemes[key];
     ...
}

答案 1 :(得分: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]);
} 

答案 2 :(得分:2)

方案是一个对象。我想你想把它变成一个对象数组。

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