5 回答

TA貢獻1873條經驗 獲得超9個贊
使用嵌套數組,并循環數組而不是硬編碼兩個數組變量。
您可以使用arrays.map()來獲取所有長度,以便計算最大長度。并對arrays.reduce()每個數組中的一個元素求和。
const addTogether = (...arrays) => {
let result = [];
let len = Math.max(...arrays.map(a => a.length));
for (let i = 0; i < len; i++) {
result.push(arrays.reduce((sum, arr) => sum + (arr[i] || 0), 0));
}
return result
}
console.log(addTogether([1, 2, 3], [4, 5], [6]));

TA貢獻1818條經驗 獲得超8個贊
解決方案:
const addTogether = (...args) => {
let result = [];
let max = 0;
args.forEach((arg)=>{
max = Math.max(max,arg.length)
})
for(let j=0;j<max;j++){
result[j]= 0
for (let i = 0; i < args.length; i++) {
if(args[i][j])
result[j]+= args[i][j]
}
}
return result
}
console.log(addTogether([1, 2, 3], [4, 5], [6]))

TA貢獻1790條經驗 獲得超9個贊
您可以在函數內部使用參數對象。
arguments
是一個可在函數內部訪問的類數組對象,其中包含傳遞給該函數的參數值。
const addTogether = function () {
? const inputs = [...arguments];
? const maxLen = Math.max(...inputs.map((item) => item.length));
? const result = [];
? for (let i = 0; i < maxLen; i ++) {
? ? result.push(inputs.reduce((acc, cur) => acc + (cur[i] || 0), 0));
? }
? return result;
};
console.log(addTogether([1,2,3], [4,5], [6]));

TA貢獻1851條經驗 獲得超4個贊
用于rest param syntax接受任意數量的參數。按外部數組的長度降序對外部數組進行排序。通過使用解構賦值將內部數組的第一個和其余部分分開。最后使用Array.prototype.map()遍歷第一個數組,因為它是最大的數組,并使用Array.prototype.reduce()方法來獲取總和。
const addTogether = (...ar) => {
ar.sort((x, y) => y.length - x.length);
const [first, ...br] = ar;
return first.map(
(x, i) => x + br.reduce((p, c) => (i < c.length ? c[i] + p : p), 0)
);
};
console.log(addTogether([1, 2, 3], [4, 5], [6]));

TA貢獻1802條經驗 獲得超4個贊
不要使用for
要求您知道每個數組長度的循環,而是嘗試使用不需要的東西。例如 -while
循環。
使用虛擬變量遞增并為每個數組重置它,并將循環終止條件設置為 - arr[i] === null
。
添加回答
舉報