萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 取得絕對值的兩種方法與效能比較

方法一:Math.abs() - 標準庫函式

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 高度優化

效能結論

  • 現代引擎 (V8, SpiderMonkey, JavaScriptCore) 對 Math.abs 有內建優化 (Intrinsic),效能極佳
  • 三元運算子 在極少數舊引擎或微基準測試中略快
  • 實務差異可忽略:每秒千萬次操作才差幾毫秒
  • 強烈建議使用 Math.abs():語意明確、可讀性高、無邊界情況 Bug

邊界情況處理

輸入Math.abs()三元運算子 (x < 0 ? -x : x)
-000
NaNNaNNaN
InfinityInfinityInfinity
-InfinityInfinityInfinity
"-5"55 (字串隱性轉換)
null00
undefinedNaNNaN
{}NaNNaN

擴充:自訂絕對值函式

// 覆寫 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()。

copyright © 萬盛學電腦網 all rights reserved