鴻蒙傳說
2022-10-08 10:24:52
晚上好,我在 Javascript 中得到了以下代碼,用戶可以在其中選擇查看將所有大于零的數(shù)字相加或計(jì)算乘積的結(jié)果,直到用戶選擇的那個(gè)(問題不要求輸入驗(yàn)證這就是為什么我沒有添加任何驗(yàn)證條件):let number = readlineSync.question("Please enter an integer greater than 0: ");let sumOrProd = readlineSync.question('Enter "s" to compute the sum, or "p" to compute the product. ');let arraynumbers = [...Array(Number(number)+1).keys()];let sumNumbers = (array) => array.reduce((acc,x)=> acc + x, 0);let multNumbers = (array) => array.reduce((acc,x)=> acc * x, 1);let userdecision = sumOrProd.toLowerCase() === 's' ? sumNumbers(arraynumbers) : multNumbers(arraynumbers);console.log(userdecision);sumNumbers()工作正常,但multNumbers()總是返回零,我不明白為什么(!?)。我已經(jīng)檢查了文檔和其他示例,但我看不出它為什么不起作用。有人可以幫我解決這個(gè)問題嗎?
1 回答

Helenr
TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊
您的數(shù)組 arraynumbers 以 0 開頭,只需刪除第一項(xiàng):
let number = 10;
let sumOrProd = 'p';
// Enter "s" to compute the sum, or "p" to compute the product.
let arraynumbers = [...Array(Number(number)+1).keys()];
arraynumbers.shift();
let sumNumbers = array => array.reduce((acc,x)=> acc + x, 0);
let multNumbers = array => array.reduce((acc,x)=> acc * x, 1);
let userdecision = sumOrProd.toLowerCase() === 's' ? sumNumbers(arraynumbers) : multNumbers(arraynumbers);
console.log(userdecision);
添加回答
舉報(bào)
0/150
提交
取消