var a = -20;
var b = Math.abs(a); // 20
// 各種輸入測試
Math.abs(-10); // 10
Math.abs(10); // 10
Math.abs(0); // 0
Math.abs(-3.14); // 3.14
Math.abs("5"); // 5 (字串自動轉數字)
Math.abs("abc"); // NaN
Math.abs(null); // 0
Math.abs(); // NaN
var a = -20;
var b = -a; // 20 (負負得正)
// 但注意:正數會變負數!
var c = 20;
var d = -c; // -20 ❌ 這不是絕對值
// 正確寫法:配合條件判斷
var abs = a < 0 ? -a : a; // 三元運算子
// 或
var abs = a >= 0 ? a : -a;
function benchmark(fn, iterations) {
var start = performance.now();
for (var i = 0; i < iterations; i++) {
fn(-Math.random() * 1000);
}
return performance.now() - start;
}
var iterations = 10000000; // 1000 萬次
var t1 = benchmark(function(x) { return Math.abs(x); }, iterations);
var t2 = benchmark(function(x) { return x < 0 ? -x : x; }, iterations);
console.log("Math.abs(): " + t1.toFixed(2) + "ms");
console.log("三元運算子: " + t2.toFixed(2) + "ms");
// 典型結果:Math.abs() 約 15-25ms,三元運算子約 10-20ms
// 差異微乎其微,現代引擎對 Math.abs 高度優化
Math.abs 有內建優化 (Intrinsic),效能極佳Math.abs():語意明確、可讀性高、無邊界情況 Bug| 輸入 | Math.abs() | 三元運算子 (x < 0 ? -x : x) |
|---|---|---|
-0 | 0 | 0 |
NaN | NaN | NaN |
Infinity | Infinity | Infinity |
-Infinity | Infinity | Infinity |
"-5" | 5 | 5 (字串隱性轉換) |
null | 0 | 0 |
undefined | NaN | NaN |
{} | NaN | NaN |
// 覆寫 Number.prototype (不推薦污染原型,僅示範)
Number.prototype.abs = function() {
return Math.abs(this.valueOf());
};
// 獨立工具函式 (推薦)
var MathUtils = {
abs: function(x) {
var n = Number(x);
return isNaN(n) ? NaN : (n < 0 ? -n : n);
},
// 陣列絕對值
absArray: function(arr) {
return arr.map(this.abs);
},
// 物件屬性絕對值
absObject: function(obj, keys) {
var result = {};
keys.forEach(function(k) {
result[k] = this.abs(obj[k]);
}, this);
return result;
}
};
// 使用
MathUtils.abs(-42); // 42
MathUtils.absArray([-1, 2, -3]); // [1, 2, 3]
JavaScript 取得絕對值**首選 Math.abs()**,語意清晰、處理邊界情況正確、現代引擎高度優化。一元負號技巧 -x 僅適用於已知為負數的情況,通用寫法需搭配條件判斷 x < 0 ? -x : x,但無實質效能優勢且易出錯。實務開發請直接使用 Math.abs()。