Math.abs()
Math.abs() 関数は、数値の絶対値を返します。
試してみましょう
構文
Math.abs(x)
引数
x-
数値です。
返値
与えられた数値の絶対値。
解説
abs() は Math オブジェクトの静的メソッドなので、 Math オブジェクトを生成してメソッドとして使用するのではなく、常に Math.abs() として使用するようにしてください (Math はコンストラクターではありません)。
例
Math.abs() の動作
空のオブジェクト、複数のメンバーを持つ配列、数値でない文字列、 undefined、 空の変数を渡すと、 NaN を返します。 null を渡すと空文字列を返し、空の配列は 0 を返します。
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 Language Specification # sec-math.abs |
ブラウザーの互換性
BCD tables only load in the browser