You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js入门者用for循环查询JSON数组未得预期结果求排查

问题排查与修复

你的代码核心问题是判断条件错误:json[i]是数组中的单个对象,而非字符串类型的国家名称,直接和"India"做全等比较永远不会成立,所以没有输出结果,count始终为0。

修复后的代码

const json = [{
    "web_pages": ["https://www.iitbbs.ac.in/"],
    "name": "IIT Bhubaneswar",
    "alpha_two_code": "IN",
    "state-province": "Odisha",
    "domains": ["iitbbs.ac.in"],
    "country": "India"
  },
  {
    "web_pages": ["http://www.davietjal.org/"],
    "name": "DAV Institute of Engineering & Technology",
    "alpha_two_code": "IN",
    "state-province": "Punjab",
    "domains": ["davietjal.org"],
    "country": "India"
  },
  {
    "web_pages": ["https://www.sciencespo-rennes.fr/en/"],
    "name": "Institut d'études politiques de Rennes",
    "alpha_two_code": "FR",
    "state-province": null,
    "domains": ["sciencespo-rennes.fr"],
    "country": "France"
  }
]

let count = 0;

for (let i = 0; i < json.length; i++) {
  // 访问对象的country属性进行判断
  if (json[i].country === "India") {
    console.log(json[i]);
    count++;
  }
}

console.log(count); // 输出2

额外建议

  • 建议用const声明json变量(如果不需要重新赋值的话),符合JavaScript最佳实践。
  • 入门后可以尝试更简洁的数组方法实现相同逻辑,比如filter:
const indianSchools = json.filter(item => item.country === "India");
console.log(indianSchools);
console.log(indianSchools.length); // 输出2

内容的提问来源于stack exchange,提问作者Zaheer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:25:39