javascript / jquery - select the larger of two numbers

喜夏-厌秋 提交于 2019-12-08 15:40:42

问题


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:

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

回答1:


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

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...

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:

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



回答2:


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

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



来源:https://stackoverflow.com/questions/13424721/javascript-jquery-select-the-larger-of-two-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!