gpt4 book ai didi

javascript - 无法使用 for 循环遍历 JavaScript 数组

转载 作者:行者123 更新时间:2023-11-30 08:42:25 24 4
gpt4 key购买 nike

我正在阅读 Eloquent Javascript 这本书,并且正在做一个练习,我无法理解我做错了什么。这是正确计算平均值的代码(祖先是一个 JSON 对象):

function average(array) {
function plus(a, b) { return a + b; }
return array.reduce(plus) / array.length;
};

function age(p) { return p.died - p.born; };

function groupBy(array, action){
var groups = {};
array.forEach(function(individual){
var group = action(individual);
if (groups[group] == undefined)
groups[group] = [];
groups[group].push(individual);
});
return groups;
};

var centuries = groupBy(ancestry, function(person){
return Math.ceil(person.died / 100);
});

console.log(average(centuries[16].map(age)));
console.log(average(centuries[17].map(age)));
console.log(average(centuries[18].map(age)));
console.log(average(centuries[19].map(age)));
console.log(average(centuries[20].map(age)));
console.log(average(centuries[21].map(age)));
// → 16: 43.5
// 17: 51.2
// 18: 52.8
// 19: 54.8
// 20: 84.7
// 21: 94

一切都很好。但是,对于我的一生,我无法弄清楚如何编写不需要最后多次调用 console.log 的代码。这是我能想到的最接近的结果,但我一直收到类型错误,我不明白为什么。

for (century in centuries) {
console.log(average(century.map(age)));
};

为什么这个 for in 循环不起作用?提前致谢!

最佳答案

Javascript 中的 for..in 循环将键值存储在您传递的变量中。

for (century in centuries) {
//here, century is the key (16, 17, etc)
//not the value of the entry in the array
console.log(average(centuries[century].map(age)));
}

关于javascript - 无法使用 for 循环遍历 JavaScript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25110315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com