【问题标题】:Search for a value within an object in javascript [closed]在javascript中搜索对象中的值[关闭]
【发布时间】:2017-04-20 22:09:33
【问题描述】:

我在一个角度范围内有一个数组,它基本上在每次迭代中都包含一个对象。我之前使用过 indexOf() 函数来检查数组中是否存在值 - 但是如何检查对象单词值中是否存在值?

我想使用 foreach 循环并检查规则数组中是否存在如下所示格式的单词 - 实现此目的的最佳方法是什么?

rules = [];

rules[0] = { word:"house"}
rules[1] = { word:"shoes"}
rules[2] = { word:"tools"}

【问题讨论】:

标签: javascript angularjs arrays object


【解决方案1】:

rules = []

rules[0] = { word:"house"}
rules[1] = { word:"shoes"}
rules[2] = { word:"tools"}
rules[3] = { sentence:"horse"}

rules.forEach(rule => {
    if (rule.word) {
      console.log('Exist. Value:', rule.word)
    } else {
      console.log('Doesn\'t Exist.')
    }
})

希望这会有所帮助!

【讨论】:

    【解决方案2】:
    for(var i =0;i < rules.length;i++){
      if(rules[i].word === 'valueYouWantToCheck'){
       // do whatever you want to do
      }
    }
    

    试试这个...:)

    【讨论】:

    • 他在问题中提到,他想使用forEach循环。
    • @bharadhwaj foreach 将提供相同的服务。只是他必须像 rules.forEach(someFunction) 一样传递 index 和 item 并编写像 someFunction(index,item) 这样的函数{}
    • 这是一个可行的解决方案,我同意!但他明确提到他想要使用forEach 循环。这就是我通知你的原因!另外他只是想知道这样的密钥word是否存在,而不是与一些价值进行比较,我希望!否则,这是一个很好的解决方案!
    • @bharadhwaj 是的,得到了​​您的关注。谢谢您指出这一点。下次我会处理这些事情...:D
    • 没有冒犯兄弟!正如我所指出的那样指出! :)
    【解决方案3】:

    你可以用这个

    var rules = [];
    rules[0] = { word:"house"}
    rules[1] = { word:"shoes"}
    rules[2] = { word:"tools"}
    rules.forEach(function(item){
       console.log(item.word)  // your word of choice
    })
    

    您也可以使用filter 函数。如果您需要的单词匹配,它将返回对象,否则它将返回一个空数组

    var getValue = rules.filter(function(item){
        return item.word=='house';
    })
     console.log(getValue)
    

    除此之外还可以使用.find方法

    rules.find(function(item){
      return item.word=="house";
    })
    

    【讨论】:

      【解决方案4】:
      rules = [];
      
      rules[0] = { word:"house"}
      rules[1] = { word:"shoes"}
      rules[2] = { word:"tools"}
      
      for(var i=0; i<rules.length ; i++)
      {
         rules[i]["word"]=='valueforComparison'; // or rules[i].word=='valueforComparison';
      }
      

      【讨论】:

        猜你喜欢
        • 2017-01-10
        • 2023-02-21
        • 2021-11-22
        • 2014-11-28
        • 1970-01-01
        • 1970-01-01
        • 2017-07-22
        • 2011-04-07
        • 2020-04-01
        相关资源
        最近更新 更多