簡體   English   中英

如何返回總數的數組 - 減少 function - Javascript

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM