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
相关产品推荐
相关产品推荐

