[英]How to return an array of the total - reduce function - Javascript
I have this array of movies, I'm trying to use the reduce function and the expected output should be: 420(the total duration of the 3 objects), the output I'm getting right now is like a concatenation of the 3 strings, why is that? I have this array of movies, I'm trying to use the reduce function and the expected output should be: 420(the total duration of the 3 objects), the output I'm getting right now is like a concatenation of the 3 strings , 这是为什么?
let movies = [ { 'name': 'Jumanji', 'duration': 120 }, { 'name': 'Harry Potter', 'duration': 60 }, { 'name': 'Toy Story', 'duration': 240 } ]; let newAr = movies.reduce((previousValue, currentValue) => [ previousValue + currentValue.duration ], []); console.log('newAr', newAr)
The previousValue
will be the accumulator, the value returned by the prior iteration of the callback - or, the initial value - so it'll be an array. previousValue
将是累加器,回调的先前迭代返回的值 - 或者,初始值 - 所以它将是一个数组。 Doing someArray + someOtherValue
will coerce the array into a string (in other words, doing .join(',')
) and concatenate it with the expression on the right.执行
someArray + someOtherValue
会将数组强制转换为字符串(换句话说,执行.join(',')
)并将其与右侧的表达式连接起来。
I'd map the movies to their durations instead, then add them up:我将 map 电影改为它们的持续时间,然后将它们相加:
const totalDuration = movies
.map(m => m.duration)
.reduce((a, b) => a + b, 0);
Or do it in one step, though it might be a bit harder to parse at a glance if you're unfamiliar with reduce
.或者一步完成,但如果您不熟悉
reduce
,可能会难以一目了然地解析。
const totalDuration = movies
.reduce((a, movie) => a + movie.duration, 0);
const movies = [ { 'name': 'Jumanji', 'duration': 120 }, { 'name': 'Harry Potter', 'duration': 60 }, { 'name': 'Toy Story', 'duration': 240 } ]; console.log(movies.reduce((previousValue, currentValue) => previousValue + currentValue.duration, 0))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.