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

[267, 306, 108]

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


当前回答

辞职拯救:

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

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

其他回答

Use:

var arr = [1, 2, 3, 4];

var largest = arr.reduce(function(x,y) {
    return (x > y) ? x : y;
});

console.log(largest);

运行这个:

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

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

您还可以扩展Array以拥有此函数,并使其成为每个数组的一部分。

Array.prototype.max = function(){return Math.max.apply( Math, this )};
myArray = [1,2,3];

console.log( myArray.max() );

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

试试这个

function largestNum(arr) {
  var currentLongest = arr[0]

  for (var i=0; i< arr.length; i++){
    if (arr[i] > currentLongest){
      currentLongest = arr[i]
    }
  }

  return currentLongest
}