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

[267, 306, 108]

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


当前回答

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

const inputArray = [1,3,4,9,16,2,20,18]; const maxNumber = Math.max(…inputArray); console.log (maxNumber);

其他回答

最简单的语法,使用新的展开操作符:

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

来源:Mozilla MDN

Use:

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

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

console.log(largest);

我不是JavaScript专家,但我想看看这些方法是如何叠加的,所以这对我来说是一个很好的练习。我不知道这在技术上是否是性能测试的正确方法,但我只是一个接一个地运行它们,正如您在代码中看到的那样。

排序和获取第0个值是目前为止最糟糕的方法(它会修改数组的顺序,这可能是不可取的)。对于其他的,差异是可以忽略不计的,除非你谈论的是数百万个索引。

5次运行100,000个索引的随机数数组的平均结果:

Reduce的运行时间为4.0392 ms Math.max.apply运行了3.3742毫秒 排序和获取第0个值花费了67.4724毫秒 数学。Max within reduce()运行了6.5804 ms 自定义findmax函数运行了1.6102 ms


var performance = window.performance

function findmax(array)
{
    var max = 0,
        a = array.length,
        counter

    for (counter=0; counter<a; counter++)
    {
        if (array[counter] > max)
        {
            max = array[counter]
        }
    }
    return max
}

function findBiggestNumber(num) {
  var counts = []
  var i
  for (i = 0; i < num; i++) {
      counts.push(Math.random())
  }

  var a, b

  a = performance.now()
  var biggest = counts.reduce(function(highest, count) {
        return highest > count ? highest : count
      }, 0)
  b = performance.now()
  console.log('reduce took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest2 = Math.max.apply(Math, counts)
  b = performance.now()
  console.log('Math.max.apply took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest3 = counts.sort(function(a,b) {return b-a;})[0]
  b = performance.now()
  console.log('sorting and getting the 0th value took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest4 = counts.reduce(function(highest, count) {
        return Math.max(highest, count)
      }, 0)
  b = performance.now()
  console.log('Math.max within reduce() took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest5 = findmax(counts)
  b = performance.now()
  console.log('custom findmax function took ' + (b - a) + ' ms to run')
  console.log(biggest + '-' + biggest2 + '-' + biggest3 + '-' + biggest4 + '-' + biggest5)

}

findBiggestNumber(1E5)

使用- Array.prototype.reduce()很酷!

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

式中acc =累加器,val =当前值;

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

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