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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3156765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:29:05  来源:igfitidea点击:

Javascript function to get the difference between two numbers

javascriptfunction

提问by Mithun Sreedharan

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。

回答by mykhal

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

回答by Salil

Here is a simple function

这是一个简单的函数

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

And as a shorter, one-line, single-argument, ternary-using arrow function

并且作为更短的、单行的、单参数的、三元使用的箭头函数

function diff (a, b) => a > b ? a - b : b - a

回答by cmcculloh

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

对比

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 方法。

回答by onurbaysan

It means you want to return absolute value.

这意味着您要返回绝对值。

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

回答by fmark

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

回答by Skorunka Franti?ek

In TypeScript, if anyone interested:

TypeScript,如果有人感兴趣:

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