如何找到数组中的最大数字

时间:2012-09-09 20:40:11

标签: javascript arrays

如何从数组中输入的数字中找到最大数字?

我已经尝试过的事情:

var largest = Math.max.apply(Math, number[i]);
var smallest = Math.min.apply(Math, number[i]);

6 个答案:

答案 0 :(得分:8)

你非常接近:

Math.max.apply(Math, number);

您需要将数组的所有元素传递给max()方法; [i]在这里没有意义。

答案 1 :(得分:3)

Math.max.apply是一个像其他答案中所说的选项,但我认为reduce在语言中更常见:

var number=[1,2,3,2,1,1]; 
number.reduce(function(a,b){return a>b ? a : b;});
// returns 3
Math.max.apply(Math.max, number);
// returns 3

答案 2 :(得分:2)

var max = number[0], i = 0;


for (i = 0; i < n; ++i) {
  if (number[i] > max) {
    max = number[i];
  }
}

或我推荐underscore.js

var max = _.max(number);

答案 3 :(得分:1)

你很接近,试试这个:

Math.max.apply(Math.max, number);

即,第二个参数将数组转换为参数列表。

(实际上因为 Math.max 从不需要 this ,所以你不需要 apply 的第一个参数;所以{{1} }或Math.max.apply(null, number)也有效。)

答案 4 :(得分:0)

function compare(a, b) {

  if (a > b) return 1
  else if (a < b) return -1
  else return 0
}

var arr = [ 1, 2, 15, 12.5, 16, 3.35 ]

arr.sort(compare)

alert( arr[2] ) // your n number


// i used sort() but because by default it sorting in lexicographical order i 
passed it throuth custom comparisom , it works fine for me

答案 5 :(得分:0)

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

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

其中 acc =累积器 val =当前值;

相关问题