我正在尝试学习数组方法链接并使用一个基本示例 - https://jsbin.com/surizinifi/edit?js,console
const data = [
{
name: 'Butters',
age: 3,
type: 'dog'
},
{
name: 'Lizzy',
age: 6,
type: 'dog'
},
{
name: 'Red',
age: 1,
type: 'cat'
},
{
name: 'Joey',
age: 3,
type: 'dog'
},
];
const ages = data
.filter(animal => animal.type === 'dog')
.map(animal => animal.age * 7)
.reduce((sum, animal) => sum + animal.age)
console.log('ages', ages);
我得到“NaN”作为数字输出(例如84)返回。你知道我在这里做错了什么吗?
最佳答案
通过映射,您将获得一个数字数组,然后不需要任何属性来求和。
一个好主意是使用累加器的起始值并防止在第一个循环中使用数组的第一个值。
const data = [
{
name: 'Butters',
age: 3,
type: 'dog'
},
{
name: 'Lizzy',
age: 6,
type: 'dog'
},
{
name: 'Red',
age: 1,
type: 'cat'
},
{
name: 'Joey',
age: 3,
type: 'dog'
},
];
const ages = data
.filter(animal => animal.type === 'dog')
.map(animal => animal.age * 7)
.reduce((sum, age) => sum + age, 0)
console.log('ages', ages);
关于JavaScript 数组方法链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58164240/