javascript - Javascript 中解决负零的优雅方法

标签 javascript arrays algorithm zero

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

例如1:

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

例2:

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

参见signed zero进行更一般性的讨论。

关于javascript - Javascript 中解决负零的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72781994/

相关文章:

Javascript Tic Tac Toe 水平检查不起作用(减少)

javascript - 如何使用 ng-if 显示列表中是否定义了某个项目

javascript - 获取对象数组中的所有参数

ios - Swift 3 将 JSON 数据排序/分组到带有部分的 TableView 中

algorithm - 运行时间,复杂性,编译时间和执行时间有什么区别?

javascript - 使用自己域的虚拟主机 (Weebly)

javascript - 如果电子邮件输入处于焦点状态,则阻止输入按钮表单提交(jquery)

C++ 2 昏暗数组新得到 0?

c# - 什么是基于规则的算法?

javascript - 舍入 n * 10 的算法