ใช้ Math.abs() เพื่อหาค่าสัมบูรณ์ (Absolute Value) ของผลลัพธ์การลบ ทำให้ได้ความต่างที่เป็นบวกเสมอ ไม่ว่าจะลบตัวไหนก่อน
ตัวอย่างจากบทความ
<html>
<head>
<script>
var num1, num2;
num1 = 50;
num2 = 35;
var difference = function (num1, num2) {
return Math.abs(num1 - num2);
}
document.write("Difference = " + difference(num1, num2)); // 15
</script>
</head>
<body></body>
</html>
วิธีการอื่นๆ
1. Ternary Operator (ไม่ต้องใช้ Math.abs)
function difference(a, b) {
return a > b ? a - b : b - a;
}
2. ใช้ Math.max และ Math.min
function difference(a, b) {
return Math.max(a, b) - Math.min(a, b);
}
3. Arrow Function (ES6)
const difference = (a, b) => Math.abs(a - b); // หรือ const diff = (a, b) => a > b ? a - b : b - a;
ขยายความสามารถ
1. รับ Array ของตัวเลข
function maxDifference(arr) {
if (arr.length < 2) return 0;
const max = Math.max(...arr);
const min = Math.min(...arr);
return max - min;
}
maxDifference([10, 5, 20, 3, 15]); // 17 (20 - 3)
2. ความต่างแบบมีเครื่องหมาย (Signed Difference)
function signedDiff(a, b) {
return a - b; // อาจเป็นลบ
}
signedDiff(10, 5); // 5
signedDiff(5, 10); // -5
3. Percentage Difference
function percentDifference(a, b) {
if (a === 0 && b === 0) return 0;
const avg = (a + b) / 2;
return Math.abs(a - b) / avg * 100;
}
percentDifference(100, 120); // 18.18%
Math.abs() Browser Support
- รองรับทุกเบราว์เซอร์ (ES1)
- ทำงานกับ Number, BigInt (ES2020)
Math.abs(-5); // 5
Math.abs(5); // 5
Math.abs(-3.14); // 3.14
Math.abs('10'); // 10 (coerce to number)
Math.abs(null); // 0
Math.abs('abc'); // NaN
Use Cases
- คำนวณระยะห่าง (Distance calculation)
- ตรวจสอบ Tolerance/Threshold
- Game development (collision detection)
- Financial calculations
- Statistics (Mean Absolute Deviation)