我目前正在學習JavaScript,并試圖測驗Spread 運算子和reduce()方法的局限性。
例子:
const numArray = [1, 6, 9, 4, 21, 8, 15];
const sumEvenOdd = numArray.reduce((acc, current) =>
current % 2 === 0
? {...acc,'even': acc.even current}
: {...acc,'odd': acc.odd current},
{"even": 0, "odd": 0}
);
console.log(sumEvenOdd); //{ even: 18, odd: 46 }
正如您從上面的代碼中看到的那樣,我能夠改變作為物件的reduce()方法的初始值:{"even": 0, "odd": 0}以跟蹤偶數和奇數的總和numArray 的數量并使用展開運算子填寫其他剩余屬性。
問題:
如果我有一個物件陣列作為初始值,我可以做同樣的事情嗎?例如,[{"even": 0}, {"odd": 0}]如果不是,我可以做些什么作為替代方法,以便我可以填寫我沒有提到的其他屬性,例如,如果物件還包含其他屬性?例如,[{"even": 0, "color": ""...}, {"odd": 0, "color": ""...}]
uj5u.com熱心網友回復:
是的,您可以使用任何道具修改陣列
您可以使用任何型別 reduce:objects, arrays, numbers, strings, boolean
幾個不同型別的例子:
const concatNumbersAsString = [0,1,2].reduce((a,c) => a c, '');
const flatNestedArrays = [[0],[1],[2]].reduce((a,c) => a.concat(c), [])
const checkBoolCondition = [0,1,2].reduce((a,c) => [1].includes(c), true)
const calculateSum = [0,1,2].reduce((a,c) => a c, 0)
console.log('concatNumbersAsString', concatNumbersAsString)
console.log('flatNestedArrays', flatNestedArrays)
console.log('checkBoolCondition', checkBoolCondition)
console.log('calculateSum', calculateSum)
修改陣列:
const numArray = [1, 6, 9, 4, 21, 8, 15];
const sumEvenOdd = numArray.reduce((acc, current) =>
current % 2 === 0
? acc.map(i => i.hasOwnProperty('even') ? {...i, even: i.even current} : i)
: acc.map(i => i.hasOwnProperty('odd') ? {...i, odd: i.odd current} : i),
[{"even": 0, color: 'red'},{ "odd": 0, color: 'green'}]
);
console.log(sumEvenOdd)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/458892.html
標籤:javascript 数组 json 算法 目的
上一篇:在引導日歷中默認選擇當前日期
下一篇:如何使游標工具提示不會離開螢屏
