Javascript函数来获取两个数字之间的差异

时间:2022-04-21 21:31:17

I want a Simple Javascript function to get the difference between two numbers in such a way that foo(2, 3) and foo(3,2) will return the same difference 1.

我想要一个简单的Javascript函数来获取两个数字之间的差异,使得foo(2,3)和foo(3,2)将返回相同的差异1。

6 个解决方案

#1


96  

var difference = function (a, b) { return Math.abs(a - b); }

#2


29  

Using ternery

使用ternery

function foo(num1, num2){
  return (num1 > num2)? num1-num2 : num2-num1
}

Or

要么

function foo(num1, num2){
  if num1 > num2
    return num1-num2
  else
    return num2-num1
}

#3


10  

Seems odd to define a whole new function just to not have to put a minus sign instead of a comma when you call it:

似乎奇怪的是定义一个全新的函数,只是为了在调用它时不必使用减号而不是逗号:

Math.abs(a - b);

vs

VS

difference(a, b);

(with difference calling another function you defined to call that returns the output of the first code example). I'd just use the built in abs method on the Math object.

(差异调用另一个您定义为调用的函数,返回第一个代码示例的输出)。我只是在Math对象上使用内置的abs方法。

#4


7  

It means you want to return absolute value.

这意味着你想要返回绝对值。

function foo(num1 , num2) {
   return Math.abs(num1-num2);
} 

#5


4  

function difference(n, m){
    return Math.abs(n - m)
}

#6


0  

In TypeScript, if anyone interested:

在TypeScript中,如果有兴趣:

public getDiff(value: number, oldValue: number) {
    return value > oldValue ? value - oldValue : oldValue - value;
}

#1


96  

var difference = function (a, b) { return Math.abs(a - b); }

#2


29  

Using ternery

使用ternery

function foo(num1, num2){
  return (num1 > num2)? num1-num2 : num2-num1
}

Or

要么

function foo(num1, num2){
  if num1 > num2
    return num1-num2
  else
    return num2-num1
}

#3


10  

Seems odd to define a whole new function just to not have to put a minus sign instead of a comma when you call it:

似乎奇怪的是定义一个全新的函数,只是为了在调用它时不必使用减号而不是逗号:

Math.abs(a - b);

vs

VS

difference(a, b);

(with difference calling another function you defined to call that returns the output of the first code example). I'd just use the built in abs method on the Math object.

(差异调用另一个您定义为调用的函数,返回第一个代码示例的输出)。我只是在Math对象上使用内置的abs方法。

#4


7  

It means you want to return absolute value.

这意味着你想要返回绝对值。

function foo(num1 , num2) {
   return Math.abs(num1-num2);
} 

#5


4  

function difference(n, m){
    return Math.abs(n - m)
}

#6


0  

In TypeScript, if anyone interested:

在TypeScript中,如果有兴趣:

public getDiff(value: number, oldValue: number) {
    return value > oldValue ? value - oldValue : oldValue - value;
}