gpt4 book ai didi

Javascript For 循环和Reduce。它是否正确

转载 作者:行者123 更新时间:2023-11-28 04:34:45 25 4
gpt4 key购买 nike

我是 JavaScript 新手,所以我一直在努力寻找方法来更多地了解它。我一直以两种方式创建代码。 For 循环和使用数组方法的高阶函数,例如reduce、map、filter 等。我将发布一个数组、一个reduce 代码和for 循环。谁能看出我的 for 循环是否正确?

var people = [
{ name: "Jesse", age: 32, gender: "male" },
{ name: "Tommi", age: 40, gender: "female" },
{ name: "John", age: 19, gender: "male" },
{ name: "Toni", age: 50, gender: "trans" },
{ name: "Gene", age: 19, gender: "trans" },
{ name: "Freddy", age: 80, gender: "male" }

];

我知道这个方法是正确的

var reduceGenderSum = people.reduce(function(obj, person){
if(!obj[person.gender]){
obj[person.gender] = 1;
} else {
obj[person.gender] += 1;
}
return obj;
}, {})

但是我不太确定这种使用 for 循环的方式,但是有人可以帮我仔细检查一下吗?

function genderSumFn(){
var count = 0;
var count2 = 0;
var count3 = 0;
for(var i = 0; i < people.length; i ++){
if(people[i].gender === 'male'){
count ++;
} else if(people[i].gender === 'female'){
count2 ++
} else {
count3 ++
}
}
return { male: count, female: count2, trans: count3 };
}

我得到相同的输出。我只是想确保我使用 for 循环正确地完成了它。

最佳答案

如果 for 循环的方法与 reduce 的回调中的方法几乎相同,您也可以使用对象。

function getGenderCount(people) {
var count = {},
i;

for (i = 0; i < people.length; i++) {
count[people[i].gender] = count[people[i].gender] || 0;
count[people[i].gender]++;
}
return count;
}

var people = [{ name: "Jesse", age: 32, gender: "male" }, { name: "Tommi", age: 40, gender: "female" }, { name: "John", age: 19, gender: "male" }, { name: "Toni", age: 50, gender: "trans" }, { name: "Gene", age: 19, gender: "trans" }, { name: "Freddy", age: 80, gender: "male" }];

console.log(getGenderCount(people));

关于Javascript For 循环和Reduce。它是否正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44322671/

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