简体   繁体   English

如何遍历数组并检查

[英]how to loop over an array and check for

I need to loop over a data structure that looks like this:我需要遍历如下所示的数据结构:

{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"}}, ...

and extract only those items for which the value searchTheme (eg "photo") is found in the themes object.并仅提取在 themes 对象中找到值 searchTheme(例如“photo”)的那些项目。

My function that is intended to accomplish this is:我旨在完成此任务的功能是:

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

    }

which returns something that looks like it's looping over the array correctly, but, for some reason, is not -- returning zero hits.它返回的东西看起来像是在正确地遍历数组,但由于某种原因,它不是——返回零命中。

在此处输入图像描述

在此处输入图像描述

I went back to the bixby example repositories on Github and found a model in the facts capsule.我回到 Github 上的 bixby 示例存储库,并在 facts capsule 中找到了一个模型。 This worked:这有效:

   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

What's different is the second line tests to see if the theme is contained in the object.不同的是第二行测试主题是否包含在对象中。 Honestly, I thought I was doing it right in my version.老实说,我认为我在我的版本中做得对。 but this one works.但是这个有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM