Javascript中的For-In循环(Node.js)意外地遍历数组索引而不是元素

我有一个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循环遍历一个Object的枚举属性,数组是对象。 你不应该使用for...in进行数组迭代

相反,使用Array构造进行迭代,比如.forEach ,或者只是使用for循环并通过其索引访问数组元素。

 ads.forEach(function (ad) { console.log(ad) }) 

你只是输出索引。 尝试

 console.log(ads[ad]);