![](/img/trans.png)
[英]JavaScript: How to return mapped array from Array.reduce() function?
[英]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 , 這是為什么?
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)
previousValue
將是累加器,回調的先前迭代返回的值 - 或者,初始值 - 所以它將是一個數組。 執行someArray + someOtherValue
會將數組強制轉換為字符串(換句話說,執行.join(',')
)並將其與右側的表達式連接起來。
我將 map 電影改為它們的持續時間,然后將它們相加:
const totalDuration = movies
.map(m => m.duration)
.reduce((a, b) => a + b, 0);
或者一步完成,但如果您不熟悉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.