How might I find the largest number contained in a

2019-01-01 06:30发布

I have a simple JavaScript Array object containing a few numbers.

[267, 306, 108]

Is there a function that would find the largest number in this array?

22条回答
临风纵饮
2楼-- · 2019-01-01 07:05

Run this:

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

And now try [3,10,2].max() returns 10

查看更多
皆成旧梦
3楼-- · 2019-01-01 07:08

I just started with JS but I think this method would be good:

var array = [34, 23, 57, 983, 198];<br>
var score = 0;

for(var i = 0; i = array.length; i++) {
  if(array[ i ] > score) {
    score = array[i];
  }
}
查看更多
只若初见
4楼-- · 2019-01-01 07:10

how about using Array.reduce ?

[0,1,2,3,4].reduce(function(previousValue, currentValue){
  return Math.max(previousValue,currentValue);
});
查看更多
深知你不懂我心
5楼-- · 2019-01-01 07:11

The easiest syntax, with the new spread operator:

var arr = [1, 2, 3];
var max = Math.max(...arr);

Source : Mozilla MDN

查看更多
刘海飞了
6楼-- · 2019-01-01 07:13

You could sort the array in descending order and get the first item:

[267, 306, 108].sort(function(a,b){return b-a;})[0]
查看更多
深知你不懂我心
7楼-- · 2019-01-01 07:13

You can also use forEach:

var maximum = Number.MIN_SAFE_INTEGER;

var array = [-3, -2, 217, 9, -8, 46];
array.forEach(function(value){
  if(value > maximum) {
    maximum = value;
  }
});

console.log(maximum); // 217

查看更多
登录 后发表回答