Math.abs() 回傳一個數字的絕對值。
Math.abs(x);
<html>
<head>
<title>JavaScript Math abs() Method</title>
</head>
<body>
<script type="text/javascript">
var value = Math.abs(-1);
document.write("First Test Value : " + value);
var value = Math.abs(null);
document.write("<br />Second Test Value : " + value);
var value = Math.abs(20);
document.write("<br />Third Test Value : " + value);
var value = Math.abs("string");
document.write("<br />Fourth Test Value : " + value);
</script>
</body>
</html>
First Test Value : 1
Second Test Value : 0
Third Test Value : 20
Fourth Test Value : NaN
這四個例子其實示範了兩種行為。傳入負數與正數如預期回傳正值;但 null 被隱式轉成數字 0,所以回傳 0;而無法轉成數字的字串 "string" 則產生 NaN。
也就是說,Math.abs() 不會對「非數字輸入」報錯,而是安靜地給你一個可能不是你想要的結果。實務上若輸入來自使用者或外部資料,建議先轉型並檢查:
var n = Number(value);
if (Number.isNaN(n)) { /* 處理非法輸入 */ }
// 兩點距離的絕對差
Math.abs(a - b);
// 限制在 [-max, max] 之外時取邊界
var clamped = Math.min(max, Math.max(-max, value));