Javascript For Loop和Reduce。这是正确的

时间:2017-06-02 06:57:13

标签: javascript for-loop

我是JavaScript的新手,所以我一直在努力想方设法了解更多。我一直在以两种方式创建代码。 for循环和高阶函数使用数组方法,如reduce,map,filter等。 我要发布一个数组,一个简化代码和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循环正确地完成它。

1 个答案:

答案 0 :(得分:0)

对于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));