JavaScript 中获取两个数字之间的差异
要获得两个数字之间的差异,请从第二个数字中减去第一个数字并将结果传递给 Math.abs()
函数,例如 Math.abs(10 - 5)
。 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
函数返回数字的绝对值。
换句话说,它返回数字与零的距离。
这里有些例子:
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
函数返回提供的数字(如果它是正数或零),如果它是负数则返回负数。
数字之间的差值始终为正数,因此
Math.abs
函数非常适合此用例。
另一种方法是使用 if 语句。
使用 if 语句获取两个数字之间的差异
要获得两个数字之间的差异,请使用 if 语句检查哪个数字更大,然后从更大的数字中减去更小的数字,例如 if (numA > numB) {return numA - numB}
。
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
if 语句检查第一个数是否大于第二个数。 如果是,我们从较大的数字中减去较小的数字并返回结果。
否则,我们知道数字相等,或者第二个数字更大,我们做相反的事情。
这比使用
Math.abs
函数更具可读性,因为该函数很少使用,而且没有多少开发人员熟悉它。
这可以通过使用三元运算符来缩短。
要获得两个数字之间的差异,请使用三元运算符来确定哪个数字较大,减去较小的数字并返回结果,例如
10 > 5 ? 10 - 5 : 5 - 10
。
const a = 10;
const b = -20;
const difference = a > b ? a - b : b - a;
console.log(difference); // 👉️ 30
三元运算符与 if/else
语句非常相似。
如果条件的计算结果为真,则返回冒号左边的表达式,否则返回冒号右边的表达式。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。