迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中获取两个数字之间的差异

作者:迹忆客 最近更新:2022/12/22 浏览次数:

要获得两个数字之间的差异,请从第二个数字中减去第一个数字并将结果传递给 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

JavaScript 中获取两个数字之间的差异.

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 语句非常相似。

如果条件的计算结果为真,则返回冒号左边的表达式,否则返回冒号右边的表达式。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便