使用 JavaScript 構造一個相對於第一個陣列元素的陣列包含加法/減法
問題
需要編寫一個 JavaScript 函式,此函式採用一個正整數陣列。我們的函式應將此陣列對映為一個字串整數陣列。
該陣列應包含我們要加到第一個元素或從第一個元素減去的數字,以獲取相應的元素。
例如
[4, 3, 6, 2]
應返回 −
['+0', '-1', '+2', '-2']
示例
以下就是程式碼 −
const arr = [4, 3, 6, 2]; const buildRelative = (arr = []) => { const res = []; let num = ''; for(let i of arr){ if(i - arr[0] >= 0){ num += '+' + (i - arr[0]) }else{ num += i - arr[0] }; res.push(num); num = ''; }; return res; }; console.log(buildRelative(arr));
輸出
[ '+0', '-1', '+2', '-2' ]
廣告