簡體   English   中英

使用條件映射函數變換數組

[英]Using conditional map function to transform array

我有一個數字數組,我想映射到一個新的數字數組。

let numbers= [1,3,5,10,11]

需要變成

var result = [4,8,15,21,11];

我嘗試使用ES6速記語法來做到這一點。 但是數字之間確實沒有任何連貫性,所以我雖然回調會更好

let numbers= [1,3,5,10,11]

const result = numbers.map(x => resultBinding(x))


function resultBinding(x){

}

現在我的問題是我不想避免避免做出很多if語句來確定每個值。

我將使用reduce來使用累加器來跟蹤先前的數組值:

 const result = [];
 array.reduce((a, b) => (result.push(a + b), b));
 result.push(array.pop()); // add the trailing 11

使用Array.map()對其進行迭代。 合並當前項和下一項(如果未定義,則為0):

 const numbers= [1,3,5,10,11] const result = numbers.map((n, i) => n + (numbers[i + 1] || 0)); console.log(result); 

結果的運算= [1 + 3、3 + 5、5 + 10、10 + 11、11]。 結果的最后一個索引與numbers數組相同,因為此后沒有索引。

 let numbers= [1,3,5,10,11]; let result = numbers.map((num, index)=> (index+1) >= numbers.length ? num : num + numbers[index+1]) console.log(result); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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