Math.abs(x) 返回數字 x 的絕對值(非負值)。無論輸入正數、負數還是零,結果均為 ≥ 0 的數值。
Math.abs(x)
x 的絕對值(數字);若無法轉換為數字,返回 NaN// 基礎用法
console.log(Math.abs(-1)); // 1
console.log(Math.abs(5)); // 5
console.log(Math.abs(0)); // 0
console.log(Math.abs(-0)); // 0
// 隱式類型轉換
console.log(Math.abs('-10')); // 10 (字符串轉數字)
console.log(Math.abs(null)); // 0 (null → 0)
console.log(Math.abs('')); // 0 (空字符串 → 0)
console.log(Math.abs('hello')); // NaN (無法轉換)
console.log(Math.abs(undefined)); // NaN
// 邊界值
console.log(Math.abs(Infinity)); // Infinity
console.log(Math.abs(-Infinity)); // Infinity
console.log(Math.abs(NaN)); // NaN
const diff = Math.abs(a - b); // a,b 之間的距離
// 判斷兩點距離是否在閾值內
function isNear(x1, y1, x2, y2, threshold) {
return Math.abs(x1 - x2) <= threshold && Math.abs(y1 - y2) <= threshold;
}
// 強制為正數
const size = Math.abs(userInput); // 防止負尺寸導致布局錯誤
// 信號處理:幅度
const amplitude = Math.abs(signal);
// 按絕對值大小排序
[-5, 2, -10, 3].sort((a, b) => Math.abs(a) - Math.abs(b));
// [2, 3, -5, -10]
// 位運算技巧(僅適用 32 位整數)
function absInt32(x) {
const mask = x >> 31;
return (x ^ mask) - mask;
}
// 測試:Math.abs 通常更快且可讀性更好
// 現代引擎已高度優化 Math.abs,無需手動優化
Math.abs(-2147483648) === -2147483648(32 位有符號整數範圍外,但 JS 數字是 64 位浮點,實際 JS 中 Math.abs(-2147483648) === 2147483648 正確)。注意:Number.MIN_SAFE_INTEGER 相關運算需謹慎。Math.abs() 是靜態方法,非數字實例方法:(-5).abs() ❌ → Math.abs(-5) ✅valueOf() 再 toString() 嘗試轉數字Math.abs() 是處理數值大小、距離、幅度的基礎工具。記住:它永遠返回非負數,且能自動處理字符串、null 等常見類型轉換。日常開發中無需手寫絕對值邏輯,直接使用此標準 API 即可。