1 回答

TA貢獻1806條經驗 獲得超5個贊
由于Array.prototype.map()
不會實時就地改變源數組,而是在循環遍歷源數組后返回新數組triangle
,因此實際上沒有訪問的意義- 它仍然是一個包含 5 個項目的稀缺數組:(由)[,,,,]
返回Array().fill()
,直到.map()
循環結束。
為了解決這個問題,您可以想出遞歸方法,或者使用Array.prototype.reduce()
:
const maxRows = 5,
? ? ? triangle = Array(maxRows)
? ? ? ? .fill()
? ? ? ? .reduce((acc, _, i) => {
? ? ? ? ? const rowData = Array(i+1)
? ? ? ? ? ? ? ? ? .fill()
? ? ? ? ? ? ? ? ? .map((__,j) =>?
? ? ? ? ? ? ? ? ? ? !j || j == i
? ? ? ? ? ? ? ? ? ? ? ? 1
? ? ? ? ? ? ? ? ? ? ? : acc[i-1][j-1] + acc[i-1][j]
? ? ? ? ? ? ? ? ? )
? ? ? ? ? acc.push(rowData)
? ? ? ? ? return acc
? ? ? ? }, [])
? ? ??
triangle.forEach(row => console.log(JSON.stringify(row)))
.as-console-wrapper{min-height:100%;}
添加回答
舉報