Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

math - Javascript max() function for 3 numbers

I need to find the highest number from 3 different numbers. The only thing I've found is max() but you can only use 2 numbers.

Whats the best way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Math.max function can accept any arbitrary number of arguments:

Syntax:

Math.max([value1[,value2[, ...]]]) 

Usage:

var max = Math.max(num1, num2, num3);

For example:

console.log(Math.max(1,2,3,4,5,6)); //  6

You could even use it to get the maximum value of an array of numbers with the help of apply:

function maxOfArray(array) {
  return Math.max.apply(Math, array);
}


let array = [1,2,3,4,5,6];
console.log(maxOfArray(array)); // 6

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...