在Javascript中获取数字的绝对值

时间:2012-02-19 22:32:12

标签: javascript

我想在JavaScript中获取数字的绝对值。也就是说,放下标志。 我在数学上知道我可以通过平方数然后取平方根来做到这一点,但我也知道这是非常低效的。

x = -25
x = x * x 
x = sqrt(x)

// x would now be 25 

JavaScript中有没有办法简单地删除一个比数学方法更有效的数字符号?

5 个答案:

答案 0 :(得分:100)

你的意思是得到一个数字的absolute valueMath.abs javascript函数完全是为此目的而设计的。

var x = -25;
x = Math.abs(x); // x would now be 25 

以下是文档中的一些测试用例:

Math.abs('-1');     // 1
Math.abs(-2);       // 2
Math.abs(null);     // 0
Math.abs("string"); // NaN
Math.abs();         // NaN

答案 1 :(得分:12)

这是获取数字绝对值的快捷方法。它适用于所有语言:

(x ^ (x >> 31)) - (x >> 31);

答案 2 :(得分:7)

答案 3 :(得分:7)

如果您想了解JavaScript如何在幕后实现此功能,可以查看此帖子。

Blog Post

以下是基于铬源代码的实现。

function MathAbs(x) {
  x = +x;
  return (x > 0) ? x : 0 - x;
}

答案 4 :(得分:1)

替代解决方案

Math.max(x,-x)

let abs = x => Math.max(x,-x);

console.log(abs(24));
console.log(abs(-24));