我需要从 3 个不同的数字中找出最大的数字。我发现的唯一东西是 max() 但你只能使用 2 个数字。
什么是最好的方法?
最佳答案
Math.max函数可以接受任意数量的参数:
语法:
Math.max([value1[,value2[, ...]]])
用法:
var max = Math.max(num1, num2, num3);
例如:
console.log(Math.max(1,2,3,4,5,6)); // 6
在 apply 的帮助下,您甚至可以使用它来获取数字数组的最大值:
function maxOfArray(array) {
return Math.max.apply(Math, array);
}
let array = [1,2,3,4,5,6];
console.log(maxOfArray(array)); // 6
如果你可以针对 ES6 (ES2015),你也可以使用 spread operator :
let array = [1,2,3,4,5,6];
let max = Math.max(...array);
console.log(max); // 6
关于3 个数字的 Javascript max() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1418569/