javascript / jquery - 选择两个数字中较大的一个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13424721/
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-10-26 18:44:07  来源:igfitidea点击:

javascript / jquery - select the larger of two numbers

javascriptjquerymathcomparisoncomparison-operators

提问by mheavers

I'm trying to use javascript to select the greater of two numbers. I know I can write an if statement, but I'm wondering if there's some sort of Math operation or something to make this more efficient. Here's how I'd do it with an if statement:

我正在尝试使用 javascript 来选择两个数字中的较大者。我知道我可以写一个 if 语句,但我想知道是否有某种数学运算或其他什么东西可以提高效率。下面是我如何用 if 语句做到这一点:

if (a > b) {
    c = a;
}  
else {
    c = b;
}

回答by BLSully

You're looking for the Max function I think....

您正在寻找我认为的 Max 函数....

var c = Math.max(a, b);

This function will take more than two parameters as well:

此函数也将采用两个以上的参数:

console.log(Math.max(4,76,92,3,4,12,9));
//outputs 92

If you have a array of arbitrary length to run through max, you can use apply...

如果你有一个任意长度的数组来运行最大值,你可以使用apply...

var arrayOfNumbers = [4,76,92,3,4,12,9];
console.log(Math.max.apply(null, arrayOfNumbers));
//outputs 92

OR if you're using ES2015+ you can use spread syntax:

或者,如果您使用的是 ES2015+,则可以使用扩展语法:

var arrayOfNumbers = [4,76,92,3,4,12,9];
console.log(Math.max(...arrayOfNumbers);
//outputs 92

回答by AntonNiklasson

c = (a > b) ? a : b;

This will do the same thing. This can be really useful and a real time saver.

这将做同样的事情。这可能非常有用并且可以实时节省时间。