我想在JavaScript中获取数字的绝对值。也就是说,放下标志。 我在数学上知道我可以通过平方数然后取平方根来做到这一点,但我也知道这非常低效。
I want to get the absolute value of a number in JavaScript. That is, drop the sign. I know mathematically I can do this by squaring the number then taking the square root, but I also know that this is horribly inefficient.
x = -25 x = x * x x = sqrt(x) // x would now be 25JavaScript中有没有办法简单地删除标志一个比数学方法更有效的数字?
Is there a way in JavaScript to simply drop the sign of a number that is more efficient than the mathematical approach?
推荐答案你的意思是得到一个数字的绝对值? Math.abs javascript函数专为此目的而设计。
You mean like getting the absolute value of a number? The Math.abs javascript function is designed exactly for this purpose.
var x = -25; x = Math.abs(x); // x would now be 25以下是文档中的一些测试用例:
Here are some test cases from the documentation:
Math.abs('-1'); // 1 Math.abs(-2); // 2 Math.abs(null); // 0 Math.abs("string"); // NaN Math.abs(); // NaN更多推荐
在Javascript中获取数字的绝对值
发布评论