1

假设我有带有这样数据的 JSON 对象(在单独的 .json 文件中):

evidenceStrings = [
{"jokeid": 0, "evidence": ["\My God you're right! I never would've thought of that!", "this look that says \My God you're right! I never would've thought of that!\", " \My God you're right! I never would've thought of that!\"]},
{"jokeid": 1, "evidence": ["the man didn't have to watch"]},
{"jokeid": 2, "evidence": ["knocking down trees with your face", "knocking down trees with your face. ", " knocking down trees with your face. ", "with your face.", "knocking down trees with your face"]}
]

我想在 HTML 文件中显示“证据”。问题是我正在从另一个 .js 文件中读取内容并使用 for 循环显示它的内容。

for(var i = 0; i < jokes.length; i++) {
    // display string at index 0 of an array in a .js file

i这里指的jokeid是JSON对象中的。现在我想要的是,对于给定的i,从 JSON 对象中提取 myevidence并显示它(最好在每个字符串后面加上一个换行符。

4

2 回答 2

1

这需要循环evidenceStrings查看是否找到了匹配的笑话ID。你可以用 很好地做到这一点.filter,但在内部它基本上做同样的事情。

for (var x = 0; x < jokes.length; x++) {
    var id = jokes[x];
    evidence = evidenceStrings.filter(function (elem) {
        return +elem.jokeid == id;
    });
    if (evidence.length == 1 && evidence[0].hasOwnProperty('evidence')) {
        console.log(evidence[0].evidence.join("\n"));
    }
}

http://jsfiddle.net/cFsze/

于 2013-02-14T21:06:51.223 回答
0

使用下划线来简化这些事情(http://underscorejs.org/):

var foundJoke = _.find(evidenceStrings,function(item) {
   return item.jokeid === 0;
});

var firstItem = _.first(foundJoke.evidence);    
if(_.isArray(foundJoke.evidence)) alert(foundJoke.evidence.join('\n'));

或者

var foundJoke = _.findWhere(evidenceStrings,{jokeid:0});
于 2013-02-14T21:12:38.570 回答