--- title: Math.abs() slug: Web/JavaScript/Reference/Global_Objects/Math/abs translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs ---
Math.abs(x) 函数返回指定数字 “x“ 的绝对值。如下:
Math.abs(x);
x由于 Math.abs() 是 Math 中的一个静态方法,你应该通过 Math.abs() 调用。(Math 不是构造器)
Math.abs()函数的行为传入一个非数字形式的字符串或者 undefined/empty 变量,将返回 NaN。传入 null 将返回 0。
Math.abs('-1'); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs("string"); // NaN
Math.abs(); // NaN
| 规范版本 | 规范状态 | 注解 |
|---|---|---|
| ECMAScript 1st Edition. Implemented in JavaScript 1.0 | Standard | Initial definition. |
| {{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}} | {{Spec2('ES5.1')}} | |
| {{SpecName('ES6', '#sec-math.abs', 'Math.abs')}} | {{Spec2('ES6')}} |