-1

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

3
  • hello, var schemes is not Array, It is JSON object, check json.org and w3schools.com/json/default.asp, it will help you, thx Commented Nov 21, 2012 at 11:29
  • @KPBird there is no such thing as a "JSON Object". JSON is a "serialisation format", which happens to look somewhat like a JS "Object literal", which is what schemes actually is. Commented Nov 21, 2012 at 11:35
  • 1
    @KPBird: NO, it's not a JSON object. schemes is a JavaScript object created through an object literal. Please see benalman.com/news/2010/03/theres-no-such-thing-as-a-json. Commented Nov 21, 2012 at 11:35

3 Answers 3

4

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];
     ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

thx a lot - coming from php so you can understand my confuseness :)
2

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

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.