我有一个简单的JavaScript数组对象包含几个数字。

[267, 306, 108]

有没有一个函数能找到这个数组中最大的数?


当前回答

运行这个:

Array.prototype.max = function(){
    return Math.max.apply( Math, this );
};

现在尝试[3,10,2].max()返回10

其他回答

辞职拯救:

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

警告:由于在某些虚拟机上参数的最大数量低至65535,如果您不确定数组有那么小,请使用for循环。

运行这个:

Array.prototype.max = function(){
    return Math.max.apply( Math, this );
};

现在尝试[3,10,2].max()返回10

Var nums = [1,4,5,3,1,4,7,8,6,2,1,4]; nums.sort (); nums.reverse (); alert (num [0]);

最简单的方法:

var nums = [1,4,5,3,1,4,7,8,6,2,1,4]; nums.sort(); nums.reverse(); alert(nums[0]);

是的,当然存在Math.max.apply(null,[23,45,67,-45]),结果是返回67。

一个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数量(…);