我有一个简单的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 = [267, 306, 108];
var largestNum = 0;
for(i=0; i<arr.length; i++) {
   if(arr[i] > largest){
     var largest = arr[i];
   }
}
console.log(largest);

辞职拯救:

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

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

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

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]);

我不是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)