我有一個陣列:
arr = [2, 4, 3, 7, 8, 2, 3, 4, 9, 1];
所有數字都低于“10”。我想要數字的累計總數。但是有兩個條件:
- 在達到最接近“10”的總數時,使總數小于或等于“10”的最后一個數字應替換為“10”和
- 累計總數從下一個數字開始。
所以,輸出應該是:
outputArr = [2, 6, 10, 10, 8, 10, 3, 10, 9, 10];
我有這個代碼:
arr = [2, 4, 3, 7, 8, 2, 3, 4, 9, 1];
total = 0;
outputArr = [];
for (i = 0; i < arr.length; i ) {
if (total arr[i] <= 10) {
total = arr[i];
outputArr.push(total);
} else {
total = arr[i];
outputArr.push(total);
}
}
console.log(outputArr);
這段代碼給了我這個輸出:
outputArr = [2, 6, 9, 7, 8, 10, 3, 7, 9, 10]
在這里,累積總數及其在達到 10 時重新啟動可以正常作業。 但是您看到的問題是:在重新啟動之前,它不能用 10 替換最后一項。
任何幫助深表感謝。
uj5u.com熱心網友回復:
您可以根據累積總和是否 < 10 或 == 10 或 > 10 來更新輸出陣列
let input = [2, 4, 3, 7, 8, 2, 3, 4, 9, 1],
output = [],
cumulative = 0;
for (let i = 0; i < input.length; i ) {
cumulative = input[i];
if (cumulative < 10) {
output.push(cumulative)
} else if (cumulative == 10) {
output.push(10)
cumulative = 0
} else {
output[i-1] = 10
cumulative = input[i]
output.push(cumulative)
}
}
console.log(output)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/506188.html
標籤:javascript 累积和
上一篇:功能關閉按鈕無法正常作業
