gpt4 book ai didi

javascript - 刚接触JS,想要显示字符串

转载 作者:行者123 更新时间:2023-11-28 02:26:16 25 4
gpt4 key购买 nike

假设我有包含这样数据的 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指的是JSON对象中的jokeid。现在我想要的是,对于给定的 i,从 JSON 对象中提取我的 evidence 并显示它(最好在每个字符串后面添加换行符。

最佳答案

这需要循环evidenceStrings来查看是否找到匹配的joiceid。您可以使用 .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/

关于javascript - 刚接触JS,想要显示字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14883950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com