[英]Why array with reduce show only one element in a new array?
我有這個 function
let arr = [1849, 81, 64, 36, 25, 16, 9, 9, 4, 1, 0];
function reducy(arr){
return arr.reduce((prevVal, item, index) => {
prevVal.push(prevVal + item * index);
return prevVal;
}, []);
}
控制台顯示:
//[
'0',
'081',
'0,081128',
'0,081,0,081128108',
'0,081,0,081128,0,081,0,081128108100',
但是我需要:
[0, 81, 128, 108, 100, 80, 54, 63, 32, 9, 0]
請幫幫我!
prevVal.push(prevVal + item * index)
您的問題是您將值與prevVal
堆疊在一起,這是一個數組。
修復應該是
prevVal.push(item * index)
完全改變
const data = [1849, 81, 64, 36, 25, 16, 9, 9, 4, 1, 0] function reducy(arr){ return arr.reduce((prevVal, item, index) => { prevVal.push(item * index); return prevVal; }, []); } console.log(reducy(data))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.