A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Math/abs below:

Math.abs() - JavaScript | MDN

Math.abs()

Baseline Widely available

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
語法 參數 回傳值

x 的絕對值。如果 x 是負數或 -0,則回傳它的相反數 -x(非負數)。否則,回傳 x 本身。因此,結果必定是正數或 0。

描述

由於 abs() 是 Math 的靜態方法,你必須使用 Math.abs(),而不是在你所建立的 Math 物件上呼叫此方法(Math 並不是建構子)。

範例 使用 Math.abs()
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。

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
規範 瀏覽器相容性 參見

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4