开发者

Javascript: traversing 2 level deep array with "for" doesn't produce another array

Sorry if my title is hard to understand. Let me explain.

To use this example of my structure:

Array
(
[2] => Array
    (
        [0] => stdClass Object
            (
                [category_id] => 2
                [category_name] => women
                [project_id] => 1
                [project_name] => Ball开发者_开发百科oons
            )

    )

[1] => Array
    (
        [0] => stdClass Object
            (
                [category_id] => 1
                [category_name] => men
                [project_id] => 2
                [project_name] => Cars
            )

        [1] => stdClass Object
            (
                [category_id] => 1
                [category_name] => men
                [project_id] => 3
                [project_name] => Houses
            )

    )

Then once i have that, i send it out to be eval'd by javascript(which is successful). Console.log does in fact shows that's my eval'd json is in fact now an object.

Now, If i console.log(myArray[2]), it will show it as an array that contains another array. Which is also correct

BUT!.. if i try to do this:

for (item in myArray[2]) {
...
}

or this:

newVar = myArray[2]
for (item in newVar) {
...
}

"item" doesn't contain the array as it should. it contains a string equal the sub arrays' key. Which in this case is "0"

What am I missing here guys? :(

Thanks for the help!


You already said what the problem was: "item" doesn't contain the array... it contains a string equal the sub arrays' key. So, you just need to use that key:

var subarray;
for (var i in myArray) {
    subarray = myArray[i];
    for (var j in subarray) {
        ... // do stuff with subarray[j]
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜