如何从数组数组中进行选择

时间:2011-01-22 23:57:34

标签: javascript jquery json

我试图比较从websockets流式传输的json数据。

像这样的数组可以完美运行:

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

但阵列数组不太好:

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

非常感谢任何帮助。提前谢谢!

function handler(jsonString) {

    var json = jQuery.parseJSON(jsonString);

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

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

}

1 个答案:

答案 0 :(得分:3)

首先从外部引用哪个内部数组[0],然后使用相同的方括号表示法,引用该内部数组[0][1]中的项。

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

所以下面的例子会产生这个:

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

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

// etc...

要遍历数组中的所有项目,您需要在循环内部循环。外部迭代存储在外部数组中的数组,而内部循环则遍历那些内部数组的值。

像这样:

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

或者如果你想要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)
    });
});

我更喜欢for循环。