Math.abs()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since 2015å¹´7æ.
Math.abs() éæ
æ¹æ³æåå³ä¸åæ¸åççµå°å¼ã
å試ä¸ä¸
function difference(a, b) {
return Math.abs(a - b);
}
console.log(difference(3, 5));
// é æè¼¸åºï¼2
console.log(difference(5, 3));
// é æè¼¸åºï¼2
console.log(difference(1.23456, 7.89012));
// é æè¼¸åºï¼6.6555599999999995
èªæ³
js
Math.abs(x)
忏
x-
ä¸åæ¸åã
åå³å¼
x ççµå°å¼ã妿 x æ¯è² æ¸æ -0ï¼ååå³å®çç¸åæ¸ -xï¼éè² æ¸ï¼ãå¦åï¼åå³ x æ¬èº«ãå æ¤ï¼çµæå¿
宿¯æ£æ¸æ 0ã
æè¿°
ç±æ¼ abs() æ¯ Math çéæ
æ¹æ³ï¼ä½ å¿
é ä½¿ç¨ Math.abs()ï¼è䏿¯å¨ä½ æå»ºç«ç Math ç©ä»¶ä¸å¼å«æ¤æ¹æ³ï¼Math 䏦䏿¯å»ºæ§åï¼ã
ç¯ä¾
>ä½¿ç¨ Math.abs()
js
Math.abs(-Infinity); // Infinity
Math.abs(-1); // 1
Math.abs(-0); // 0
Math.abs(0); // 0
Math.abs(1); // 1
Math.abs(Infinity); // Infinity
忏çå¼·å¶è½å
Math.abs() æå°åæ¸å¼·å¶è½åçºæ¸åãç¡æ³è½åçå¼å°è®çº NaNï¼å æ¤ Math.abs() 乿åå³ NaNã
js
Math.abs("-1"); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs(""); // 0
Math.abs([]); // 0
Math.abs([2]); // 2
Math.abs([1, 2]); // NaN
Math.abs({}); // NaN
Math.abs("string"); // NaN
Math.abs(); // NaN
è¦ç¯
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-math.abs> |