Reputation: 729
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
Upvotes: -1
Views: 61
Reputation: 94469
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)
}
Upvotes: 2
Reputation: 339816
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];
...
}
Upvotes: 4
Reputation: 22659
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]);
}
Upvotes: 2