最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to Select from an array of arrays - Stack Overflow

programmeradmin1浏览0评论

I'm trying to pare json data being streamed in from websockets.

An array like this would work flawlessly:

["stream","apple","orange"]

But an array of arrays not so well:

[["stream","apple","orange"],["stream","pear","kiwi"],["stream","apple","juice"]]

Any help would be greatly appreciated. Thanks in advance!

function handler(jsonString) {

    var json = jQuery.parseJSON(jsonString);

    if (json[0] == "blah") {
       //Do something
    }

    else if (json[0] == "blah2") {
        //Do something else
    }

}

I'm trying to pare json data being streamed in from websockets.

An array like this would work flawlessly:

["stream","apple","orange"]

But an array of arrays not so well:

[["stream","apple","orange"],["stream","pear","kiwi"],["stream","apple","juice"]]

Any help would be greatly appreciated. Thanks in advance!

function handler(jsonString) {

    var json = jQuery.parseJSON(jsonString);

    if (json[0] == "blah") {
       //Do something
    }

    else if (json[0] == "blah2") {
        //Do something else
    }

}
Share Improve this question edited Jan 23, 2011 at 0:00 user113716 323k64 gold badges453 silver badges441 bronze badges asked Jan 22, 2011 at 23:57 DrEvalDrEval 411 silver badge2 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

First reference which inner Array you want [0] from the outer, then using the same square bracket notation, reference the item in that inner Array [0][1].

if (json[0][0] == "blah") {
   //Do something
}
else if (json[0][1] == "blah2") {
    //Do something else
}

So the following examples would produce this:

json[0][0];  // "stream"
json[0][1];  // "apple"

json[1][0];  // "stream"
json[1][1];  // "pear"

// etc...

To iterate over all the items in the Arrays, you'd need a loop inside a loop. The outer one to iterate through the Arrays stored in the outer Array, and the inner loop to iterate through the values of those inner Arrays.

Like this:

for( var i = 0, len_i = json.length; i < len_i; i++ ) {
    for( var j = 0, len_j = json[ i ].length; j < len_j; j++ ) {
        // do something with json[ i ][ j ]; (the value in the inner Array)
    }
}

or if you wanted jQuery.each()(docs):

jQuery.each( json, function(i,val) {
    jQuery.each( val, function(j,val_j) {
        // do something with val_j (the value in the inner Array)
    });
});

I'd prefer the for loops though.

发布评论

评论列表(0)

  1. 暂无评论