【问题标题】:Unable to fetch a key data while iterating through an object迭代对象时无法获取关键数据
【发布时间】:2022-01-20 23:05:37
【问题描述】:

我正在遍历一个对象。但是,它并没有抓住所有的钥匙。它只捕获了一些。尤其是没有捕捉到 organic_results 键。我不明白为什么。请帮忙。

 for (var key in this.writeItOutput){ 
    
      if(key == "inline_people_also_search_for"){
      console.log("inline_people_also_search_for")
    }

} 
 
  if(key == 'organic_results'){

    console.log("inside organic_results");
}

  if(key =="related_questions"){
console.log("inside related questions");
 
}


  if(key =="related_searches"){
 console.log("Inside related_searches");
}
      
}

所有的键是:

【问题讨论】:

标签: javascript angular object


【解决方案1】:

你有一个括号,在这一行之前关闭你的 for-in 循环:

if(key == 'organic_results'){

所以您的脚本执行的步骤如下:

  1. 开始for-in循环

  2. key 变量设置为来自this.writeItOutput 迭代的键

  3. 检查key 是否等于“inline_people_also_search_for”

  4. 转到第 2 步,直到 this.writeItOutput 中的所有键都被迭代

  5. 结束循环

  6. 如果有块则运行

因此,当您到达第 5 步时,您的 key 变量仅等于 this.writeItOutput 中的一个键。您可能想要做的是将所有这些 if 块放在您的 for-in 循环中:

for (var key in this.writeItOutput){ 
   if(key == "inline_people_also_search_for"){
     console.log("inline_people_also_search_for")
   }

// } - this bracket is the problem
 
  if(key == 'organic_results'){
    console.log("inside organic_results");
  }

  if(key =="related_questions"){
    console.log("inside related questions");
  }


  if(key =="related_searches"){
    console.log("Inside related_searches");
  }
      
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-02
    • 2016-02-08
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    相关资源
    最近更新 更多