gpt4 book ai didi

javascript - 根据给定值将运算从求和更新为减法,反之亦然

转载 作者:行者123 更新时间:2023-12-01 02:18:24 25 4
gpt4 key购买 nike

我需要对数组的值求和或相减。

例如:

[1, 5, 10] 应表示为:1 + 5 + 10 = 16

并且 [1, 5, -1, 10, 5] 应该是:1 + 5 - 10 - 5-1 number 表示减法或求和,具体取决于 -1 的位置。第一个 -1 表示减法,第二个 -1 表示一切都回到了正常的总和,因为一切都在一开始,第三个将再次减法, 等等。

现在看看 2 个 -1 应该是什么样的:[1, 5, -1, 10, 5, -1, 5, 5],它应表示为:1 + 5 - 10 - 5 + 5 + 5,明白了吗?

因此,所有内容都应该求和,直到数组包含 -1 为止,因此它变为减法,如果还有另一个 -1 操作应更改为和。依此类推,每次出现新的“-1”时,操作都会与之前相反。

我正在这样计算:

function calculate (){

logingValues();
var total = 0;
var shouldSubtract = false;

for (var i = 0; i < arrayOfNumbers.length; i++) {
if (arrayOfNumbers[i] === "") continue;
var currentNumber = parseInt(arrayOfNumbers[i], 10);

if(isNaN(currentNumber)) {
currentNumber = 0;
}

if (currentNumber === -1) {
shouldSubtract = true;
} else {
if (shouldSubtract) {
total -= currentNumber;
shouldSubtract = false;
} else {
total += currentNumber;
}
}
}
caculationEffect(total);
}

And here is the whole code

有什么建议吗?

最佳答案

您可以使用变量来决定是否添加或减去实际值。

function sum(array){
var negative;
return array.reduce(function (a, b) {
if (b === -1) {
negative = !negative;
return a;
}
return negative ? a - b : a + b;
}, 0);
}

console.log(sum([1, 5, 10]));
console.log(sum([1, 5, -1, 10, 5]));
console.log(sum([1, 5, -1, 10, 5, -1, 5, 5]));

关于javascript - 根据给定值将运算从求和更新为减法,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38250310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com