简体   繁体   中英

javascript array basics

Im trying to improve my javascript an running into somewhat of a dead end here.

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"]
    }
};

This is my array.

Im then trying to do a for each (as I know from php), but it seems javascript thinks schemes is an object and thus unable to do a:

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

What am I missing? schemes.length says undefined

schemes is indeed an "object", and as such has no .length .

You can use Object.keys(schemes) to obtain an array of the keys, or:

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

You are missing the fact that schemes is actually an object, not an array.

Consider the following:

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

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

And what you can do with these variables:

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

Schemes is an object. I think you want to make it an array of objects.

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"]
    }
}];

You can then traverse the array as follows:

for (var i=0;i<schemes.length;i++) {
  alert(schemes[i].creatures[1]); //alerts creature1 (2x)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM