Javascript (Node.js) 中的 For-In 循环意外遍历数组索引而不是元素
For-In loop in Javascript (Node.js) unexpectedly iterates through array indexes instead of elements
我有一个 Node.js 脚本,它读取和解析 JSON 文件的内容并遍历其根数组的元素;当我尝试检查此类迭代的对象时,我遇到了一些意想不到的结果;被迭代的对象似乎是被迭代元素的索引。
这是脚本:
if (process.argv.length != 3) {
console.log("Usage: node chooseAdAmongAds.js /path/to/ads.json");
process.exit(9);
}
fs = require("fs");
var content = fs.readFileSync(process.argv[2], "utf8")
var ads = JSON.parse(content);
for (ad in ads) {
console.log(ad);
}
JSON 文件:
[
{
"impressions": 131,
"ID": 514,
"investment": 2
},
{
"impressions": 880,
"ID": 451,
"investment": 5
},
{
"impressions": 135,
"ID": 198,
"investment": 9
},
{
"impressions": 744,
"ID": 262,
"investment": 8
},
{
"impressions": 234,
"ID": 954,
"investment": 19
},
{
"impressions": 673,
"ID": 274,
"investment": 12
},
{
"impressions": 442,
"ID": 734,
"investment": 6
},
{
"impressions": 453,
"ID": 982,
"investment": 5
},
{
"impressions": 55,
"ID": 275,
"investment": 5
},
{
"impressions": 628,
"ID": 524,
"investment": 1
}
]
控制台输出:
iMac-di-Michele:Node.js michele$ node chooseAdAmongAds.js example.json
0
1
2
3
4
5
6
7
8
9
iMac-di-Michele:Node.js michele$
为什么会这样?
for...in
遍历对象的可枚举属性,数组是对象。 You should not use for...in
for array iteration
相反,使用 Array 构造进行迭代,例如 .forEach
,或者只使用 for
循环并通过其索引访问数组元素。
ads.forEach(function (ad) {
console.log(ad)
})
您只是在输出索引。尝试
console.log(ads[ad]);
我有一个 Node.js 脚本,它读取和解析 JSON 文件的内容并遍历其根数组的元素;当我尝试检查此类迭代的对象时,我遇到了一些意想不到的结果;被迭代的对象似乎是被迭代元素的索引。 这是脚本:
if (process.argv.length != 3) {
console.log("Usage: node chooseAdAmongAds.js /path/to/ads.json");
process.exit(9);
}
fs = require("fs");
var content = fs.readFileSync(process.argv[2], "utf8")
var ads = JSON.parse(content);
for (ad in ads) {
console.log(ad);
}
JSON 文件:
[
{
"impressions": 131,
"ID": 514,
"investment": 2
},
{
"impressions": 880,
"ID": 451,
"investment": 5
},
{
"impressions": 135,
"ID": 198,
"investment": 9
},
{
"impressions": 744,
"ID": 262,
"investment": 8
},
{
"impressions": 234,
"ID": 954,
"investment": 19
},
{
"impressions": 673,
"ID": 274,
"investment": 12
},
{
"impressions": 442,
"ID": 734,
"investment": 6
},
{
"impressions": 453,
"ID": 982,
"investment": 5
},
{
"impressions": 55,
"ID": 275,
"investment": 5
},
{
"impressions": 628,
"ID": 524,
"investment": 1
}
]
控制台输出:
iMac-di-Michele:Node.js michele$ node chooseAdAmongAds.js example.json
0
1
2
3
4
5
6
7
8
9
iMac-di-Michele:Node.js michele$
为什么会这样?
for...in
遍历对象的可枚举属性,数组是对象。 You should not use for...in
for array iteration
相反,使用 Array 构造进行迭代,例如 .forEach
,或者只使用 for
循环并通过其索引访问数组元素。
ads.forEach(function (ad) {
console.log(ad)
})
您只是在输出索引。尝试
console.log(ads[ad]);