Number 2 ? Number 1 : Number 2;"."> How to find the maximum value of two numbers in JavaScript-JS Tutorial-php.cn

How to find the maximum value of two numbers in JavaScript

青灯夜游
Release: 2022-02-09 14:55:13
Original
6283 people have browsed it

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

How to find the maximum value of two numbers in JavaScript

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));
Copy after login

How to find the maximum value of two numbers in JavaScript

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 ;
Copy after login

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));
Copy after login

How to find the maximum value of two numbers in JavaScript

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));
Copy after login

How to find the maximum value of two numbers in JavaScript

[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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!