JavaScript:获取两个数字之间的差值
介绍三种获取JavaScript中两个数字之间的差值的方法
第一种:使用
Math.abs() 函数function getDifference(a, b) {
return Math.abs(a - b);
}
console.log(getDifference(10, 15)); // 👉️ 5
console.log(getDifference(15, 10)); // 👉️ 5
console.log(getDifference(-10, 10)); // 👉️ 20
注意Math.abs() 只有一个参数的情况下返回的是 0 - 输入值之间绝对值
console.log(Math.abs(-3)); // 👉️ 3
console.log(Math.abs(-3.5)); // 👉️ 3.5
console.log(Math.abs(-0)); // 👉️ 0
console.log(Math.abs(3.5)); // 👉️ 3.5
console.log(Math.abs('-3.5')); // 👉️ 3.5
注意:Math.abs()函数之间的差值为正数,不会输出负数,如下面示例
console.log(getDifference(-5, -3));// 👉️ 2 而不是 -2
第二种:使用
if 判断语句function getDifference(a, b) {
if (a > b) {
return a - b;
}
return b - a;
}
console.log(getDifference(10, 15)); // 👉️ 5
console.log(getDifference(15, 10)); // 👉️ 5
console.log(getDifference(-10, 10)); // 👉️ 20
console.log(getDifference(-10, -3));// 👉️ 7
第二种:使用
三元运算符const a = 10; const b = -20; const difference = a > b ? a - b : b - a; console.log(difference); // 👉️ 30
文章评论