在Javascript中解决负零的优雅方法



我必须乘以数组中所有元素的符号。

例如1:

input: [1, 2, 3]
output: 1
Explain: 1 * 1 * 1 = 1

Ex2:

input: [1, -2, 3]
output: -1
Explain: 1 * (-1) * 1 = -1

示例3:

input: [1, -2, 3, 0]
output: 0
Explain: 1 * (-1) * 1 * 0 = 0

这是我的解决方案

function cal(A)
{
return A.reduce((total, currentValue) => total * Math.sign(currentValue), 1);
}

然而,ex3的cal([1, -2, 3, 0])的输出是-0

我已经考虑过再增加一个条件,比如这个

function cal(A)
{
var total = A.reduce((total, currentValue) => total * Math.sign(currentValue), 1);
if(total === 0)
return 0;
else
return total;
}

很明显,它看起来很难看。有没有更优雅的方法来解决这个问题?

为了避免条件检查并保持函数纯粹的计算性,您可以使用-0的奇怪规则简单地将0添加到reduce()的结果中,这对非零结果没有影响,但会将-0转换为0

function cal(arr) {
return arr.reduce((a, c) => a * Math.sign(c), 1) + 0;
}
console.log(cal([1, 2, 3]));     // 1
console.log(cal([1, -2, 3]));    // -1
console.log(cal([1, -2, 3, 0])); // 0

有关更多一般性讨论,请参阅签名零。

在您的示例中,不需要将所有值相乘。如果至少有一个零,则结果为零,因此不需要遍历整个数组。以下示例:

function compute(arr)
{
let result = true;
for (let item of arr) {
if (item === 0) return 0;
if (item < 0) result = !result;
}
return result ? 1 : -1;
}
console.log(compute([1, 2, 3]));
console.log(compute([1, -2, 3]));
console.log(compute([1, -2, 3, 0]));

最新更新