JavaScript method to find the maximum of two numbers: 1. Use the max() method of the Math object, the syntax is "Math.max(number 1, number 2);"; 2. Use the ternary operator , the syntax is "Number 1>Number 2? Number 1:Number 2;".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
JavaScript method to find the maximum of two numbers
1. Use the max() method of the Math object
max() method returns the number with the highest value.
console.log(Math.max(5, 10)); console.log(Math.max(10, 6)); console.log(Math.max(8, -1)); console.log(Math.max(2, 2.5)); console.log(Math.max(10, 10));
2. Use the ternary operator
The ternary operator (also known as the conditional operator) is composed of It consists of a question mark and a colon, and the syntax format is as follows:
条件表达式 ? 表达式1 : 表达式2 ;
If the result of "conditional expression" is true (true), the code in "expression 1" will be executed, otherwise "expression 2" will be executed "code in ".
Example:
function max(first,second){ return first > second ? first : second; } console.log(max(2,3)); console.log(max(2,1)); console.log(max(-2,3));
3. Use if statement
function max(first, second) { if (first > second) { return first } else { return second }; } console.log(max(2, 3)); console.log(max(2, 1)); console.log(max(-2, 3));
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to find the maximum value of two numbers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!