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:15

Yes of course exist: Math.max.apply(null,[23,45,67,-45]) and the result return 67;

查看更多
情到深处是孤独
3楼-- · 2019-01-01 07:15

Try this

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

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

  return currentLongest
}
查看更多
牵手、夕阳
4楼-- · 2019-01-01 07:16

How about this:

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

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

console.log(largest);
查看更多
泪湿衣
5楼-- · 2019-01-01 07:16

Using - Array.prototype.reduce() is cool!

[267, 306, 108].reduce((acc,val)=> (acc>val)?acc:val)

where acc = accumulator and val = current value;

var a = [267, 306, 108].reduce((acc,val)=> (acc>val)?acc:val);

console.log(a);

查看更多
登录 后发表回答