不確定我是否過于復雜,但我試圖得到這個陣列陣列中所有數字的總和:
const frames = [
[2, 0], [4, 2], [6, 0], [2, 4], [1, 5], [7, 0], [5, 2], [7, 0], [2, 6], [8, 1]
]
我正在練習使用map并reduce這樣做:
const score = (frames) =>{
console.log(frames)
let addedScores = frames.map(frame.reduce((previousValue, currentValue) => previousValue currentValue))
console.log(addedScores)
}
但目前收到此錯誤:
TypeError: 2,04,26,02,41,57,05,27,02,68,1 is not a function
at Array.map (<anonymous>)
at score (/Users/x/Desktop/Programming/devacademy/bootcamp/week1/preparation/bowling-kata/game.js:8:28)
at Object.<anonymous> (/Users/x/Desktop/Programming/devacademy/bootcamp/week1/preparation/bowling-kata/game.js:17:1)
這是一個小提琴版本。
任何建議和解釋將不勝感激
uj5u.com熱心網友回復:
你幾乎就在那里!如果您查看堆疊跟蹤所面臨的錯誤,您將看到Array.map函式引發了錯誤,即“stuff”(即2,04,26,02,41,57,05,27,02,68,1)不是“函式”。
map高階函式需要一個函式,它將映射到 的元素frames。
你想要的是這樣的:
//...
let addedScores = frames.map((frame) => frame.reduce((previousValue, currentValue) => previousValue currentValue))
//...
在這里,我僅將您的addedScores運算式轉換為將匿名函式傳遞(frame) => { ... }給map函式。
希望這可以幫助!
的結果形狀addedScores將是:[2, 6, 6, 6, 6, 7, ...],它是 中每對數字的總和frames。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/480942.html
標籤:javascript 减少 array.prototype.map
