开发者

Syntax for parsing the Nth item from JSON array using JQuery

I've seen many JQuery examples that make use of $.each to loop through a JSON array. However, what need to do is individually grab items 0 - 3 and pass them to another function called "Search". Here's what I've come up with.

        $.getJSON("http://localhost:61741/binggame/play?cat=Body%20Parts", {
        tags: "English",
        tagmode: "any",
        format: "json"

    },


function (data) {

    Search(data.items[0], "Box1_Image");
    Search(data.items[1], "Box2_Image");
    Search(data.items[2], "Box3_Image");
    Search(data.items[3], "Box4_Image");
});

I'm fairly certain that data.items[] is not the correct syntax.

Here's a sample of my JSON:

{"nouns":[
    {
        "ID":26,
        "Category":"Body Parts",
        "English":"muscle",
        "Pinyin":"gei yUk",
        "Image1":null,
        "Audio1":null
    },
    {
        "ID":27,
        "Category":"Body Parts",
        "English":"neck",
        "Pinyin":"gen",
        "Image1":null,
        "Audio1":null
    },
    {
        "ID":28,
        "Category":"Body Parts",
        "English":"nose",
        "Pinyin":"bei",
        "Image1":null,
        "Audio1":null
    },
    {
        "ID":29,
        "Category":"Body Par开发者_JAVA百科ts",
        "English":"rib",
        "Pinyin":"lat gwt",
        "Image1":null,
        "Audio1":null
    }
]}

For this sample, the value of data.items[0] should be "muscle", data.items[1] should be "neck", data.items[2] should be "nose" and data.items[3] should be "rib".

Can someone point out to me what I've done wrong?


Can someone point out to me what I've done wrong?

To start, there is no property names items in your JSON.


If you want to get "muscle": data.nouns[0].English

If you want to get "neck": data.nouns[1].English

and so on:

function (data) {

    Search(data.nouns[0].English, "Box1_Image");
    Search(data.nouns[1].English, "Box2_Image");
    Search(data.nouns[2].English, "Box3_Image");
    Search(data.nouns[3].English, "Box4_Image");
});

or, to stay DRYer:

function (data) {
    var nouns = data.nouns;

    function getNoun(i) {
        return nouns[i].English;
    }

    Search(getNoun(0), "Box1_Image");
    Search(getNoun(1), "Box2_Image");
    Search(getNoun(2), "Box3_Image");
    Search(getNoun(3), "Box4_Image");
});

or better still:

function (data) {
    var nouns = data.nouns;

    for (var i=0; i<4; i++) {
        Search(nouns[i].English, 'Box' + (i+1) + '_Image');
    }
});


I assume you are manipulating the list in the nouns property and in that case it would be:

for (var i = 0, l = data.nouns.length; i < l; i++) {
    Search(data.nouns[i].English, 'Box' + (i + 1) + '_Image');
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜