我有一个简单的JavaScript数组对象包含几个数字。
[267, 306, 108]
有没有一个函数能找到这个数组中最大的数?
我有一个简单的JavaScript数组对象包含几个数字。
[267, 306, 108]
有没有一个函数能找到这个数组中最大的数?
当前回答
您还可以扩展Array以拥有此函数,并使其成为每个数组的一部分。
Array.prototype.max = function(){return Math.max.apply( Math, this )};
myArray = [1,2,3];
console.log( myArray.max() );
其他回答
辞职拯救:
Array.max = function( array ){
return Math.max.apply( Math, array );
};
警告:由于在某些虚拟机上参数的最大数量低至65535,如果您不确定数组有那么小,请使用for循环。
要找到数组中最大的数字,您只需要使用Math.max(…arrayName);。它是这样工作的:
let myArr = [1, 2, 3, 4, 5, 6];
console.log(Math.max(...myArr));
要了解更多关于Math.max的信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
Use:
var arr = [1, 2, 3, 4];
var largest = arr.reduce(function(x,y) {
return (x > y) ? x : y;
});
console.log(largest);
你可以使用apply函数,调用Math.max:
var array = [267, 306, 108];
var largest = Math.max.apply(Math, array); // 306
它是如何工作的?
apply函数用于调用具有给定上下文和参数的另一个函数,以数组形式提供。min和max函数可以接受任意数量的输入参数:Math。Max (val1, val2,…valN)
如果我们调用:
Math.min.apply(Math, [1, 2, 3, 4]);
apply函数将执行:
Math.min(1, 2, 3, 4);
注意,第一个参数context对于这些函数并不重要,因为它们是静态的。不管传递什么作为上下文,它们都将工作。
一个for/of循环解决方案:
Const数= [2,4,6,8,80,56,10]; const findMax =(…numbers) => { let currentMax = numbers[0];/ / 2 For (const number of numbers) { if (number > currentMax) { console.log(数字,currentMax); currentMax = number; } } console.log('最大',currentMax); 返回currentMax; }; findMax数量(…);