如何在reduce()中返回累加器的长度

时间:2018-07-30 22:24:17

标签: javascript reduce

我正在学习JavaScript中的 Reduce 迭代器,我正在尝试检查累加器的长度,但是它一直返回 TypeError:无法读取未定义的属性'length'

这是我正在使用的数组

var songs = [
{
    name: 'Smooth',
    artist: 'Santana featuring Rob Thomas',
    year: 1999,
    month: 10,
    day: 23,
    weeksAtNumberOne: 12,
    duration: '4:00',
},
{
    name: 'What a Girl Wants',
    artist: 'Christina Aguilera',
    year: 2000,
    month: 6,
    day: 15,
    weeksAtNumberOne: 2,
    duration: '3:20',
},
{
    name: 'I Knew I Loved You',
    artist: 'Savage Garden',
    year: 2000,
    month: 8,
    day: 29,
    weeksAtNumberOne: 4,
    duration: '4:10',
},
{
    name: 'Thank God I Found You',
    artist: 'Mariah Carey featuring Joe and 98 Degrees',
    year: 2000,
    month: 2,
    day: 19,
    weeksAtNumberOne: 2,
    duration: '4:17',
},
{
    name: 'Amazed',
    artist: 'Lonestar',
    year: 2000,
    month: 7,
    day: 4,
    weeksAtNumberOne: 2,
    duration: '4:00',
}]

代码

function summerCount(arr) {
return arr.reduce(function(init, next) {
    if ([6,7,8].includes(next.month)) {
        init.push(next.month);
    };
     return init.length;
}, [])};

如果我只返回 init ,它将返回数组,但是如果我添加 .length 属性,则将引发TypeError。 预先谢谢你

2 个答案:

答案 0 :(得分:1)

您应该仅在所有迭代完成后才检查累加器的长度,而不是在此之前,否则,下一次迭代中累加器的值将是数字,而不是数组(并且代码取决于累加器始终为< em> array ):

{{1}}

答案 1 :(得分:1)

当您在return init.lengthreduce()成为下一个累加器时。因此,下次通过reduce尝试在整数上寻找length属性,这是行不通的(如您所注意到的)。

如果需要长度,只需使用reduce即可返回数组(return init),然后查看返回的数组的长度。

如果您只是想要计数,则在遍历并返回数字时将其添加到累加器中:

var songs = [{name: 'Smooth',artist: 'Santana featuring Rob Thomas',year: 1999,month: 10,day: 23,weeksAtNumberOne: 12,duration: '4:00',},{name: 'What a Girl Wants',artist: 'Christina Aguilera',year: 2000,month: 6,day: 15,weeksAtNumberOne: 2,duration: '3:20',},{name: 'I Knew I Loved You',artist: 'Savage Garden',year: 2000,month: 8,day: 29,weeksAtNumberOne: 4,duration: '4:10',},{name: 'Thank God I Found You',artist: 'Mariah Carey featuring Joe and 98 Degrees',year: 2000,month: 2,day: 19,weeksAtNumberOne: 2,duration: '4:17',},{name: 'Amazed',artist: 'Lonestar',year: 2000,month: 7,day: 4,weeksAtNumberOne: 2,duration: '4:00',}]

function summerCount(arr) {
  return arr.reduce((init, next) => init + ([6,7,8].includes(next.month) ? 1 : 0)
  , 0)
}
console.log(summerCount(songs))