gpt4 book ai didi

javascript - 如何循环数组并检查

转载 作者:行者123 更新时间:2023-12-02 22:23:53 25 4
gpt4 key购买 nike

我需要循环一个如下所示的数据结构:

{tags: ["stonehenge"], text: "At about 40m high, Silbury Hill is the highest prehistoric mound in Europe and about the size of one of the smaller pyramids of the Giza Necropolis in Egypt. Construction started about 2400BC and is estimated (by R J C Atkinson) to have taken 500 men working full-time about 15 years to complete. It is hard to see how a single tribe could have found this man-power; rather it seems necessary to envisage a much larger social structure. The monument is contemporary with Stonehenge and part of the Stonehenge World Heritage Site, close to Avebury. Its function is not known.", speech: "Silbury Hill, built starting in 2400 BC, is the highest prehistoric mound in Europe and about the size of one of the smaller pyramids of the Giza Necropolis in Egypt.", title: ["Silbury Hill"], themes: ["photo", "Avebury", "UNESCO WHS"], image: {url: "images/Silbury_Hill.jpg"}}, ...

并仅提取那些在主题对象中找到值 searchTheme(例如“照片”)的项目。

我旨在完成此任务的函数是:

  console.log ("ready to search for searchTheme", searchTheme,"in", items.length,  "items")

for (var j = 0; j < items.length; j++) {
for (var k = 0; k < items[j].themes.length; k++)
console.log("examining item", j, "theme", k, "which is", items[j].themes[k],"for match with", searchTheme)
if (searchTheme == items[j].themes[k] {
console.log ("that was a match")
matches.push(items[k])}

}

它返回的东西看起来像是正确地循环数组,但由于某种原因,它不是——返回零命中。

enter image description here

enter image description here

最佳答案

我回到 Github 上的 bixby 示例存储库,并在事实胶囊中找到了一个模型。这有效:

   for (var i = 0; i < items.length; i++) {
if (items[i].themes) {
for (var j = 0; j < items[i].themes.length; j++) {
if (searchTheme == items[i].themes[j].toLowerCase()) {
matches.push(items[i])
break
}
}
}
}
return matches

不同的是第二行测试主题是否包含在对象中。老实说,我认为我在我的版本中做得对!但这是有效的。

关于javascript - 如何循环数组并检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59129720/

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