问题
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