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 06:52

Resig to the rescue:

Array.max = function( array ){
    return Math.max.apply( Math, array );
};
查看更多
与君花间醉酒
3楼-- · 2019-01-01 06:52

Finding max and min value the easy and manual way. This code is much faster than Math.max.apply; I have tried up to 1000k numbers in array.

function findmax(array)
{
    var max = 0;
    var a = array.length;
    for (counter=0;counter<a;counter++)
    {
        if (array[counter] > max)
        {
            max = array[counter];
        }
    }
    return max;
}

function findmin(array)
{
    var min = array[0];
    var a = array.length;
    for (counter=0;counter<a;counter++)
    {
        if (array[counter] < min)
        {
            min = array[counter];
        }
    }
    return min;
}
查看更多
姐姐魅力值爆表
4楼-- · 2019-01-01 06:52

You can try this,

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);
查看更多
墨雨无痕
5楼-- · 2019-01-01 06:53

Find Max and Min value using Bubble Sort

    var arr = [267, 306, 108];

    for(i=0, k=0; i<arr.length; i++) {
      for(j=0; j<i; j++) {
        if(arr[i]>arr[j]) {
          k = arr[i];
          arr[i] = arr[j];
          arr[j] = k;
        }
      }
    }
    console.log('largest Number: '+ arr[0]);
    console.log('Smallest Number: '+ arr[arr.length-1]);

查看更多
宁负流年不负卿
6楼-- · 2019-01-01 06:54

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

查看更多
爱死公子算了
7楼-- · 2019-01-01 06:55

Don't forget that the wrap can be done with Function.prototype.bind, giving you an "all-native" function.

var aMax = Math.max.apply.bind(Math.max, Math);
aMax([1, 2, 3, 4, 5]); // 5
查看更多
登录 后发表回答