1. apply方法
var a = [3, 2, 1];
var max = Math.max.apply(Math, a);
console.log( max );
因为Math.max的参数是传入一些参数,而不是数组,无法直接使用,可以用apply方法。
2. reduce方法
var a = [3, 2, 1];
var max = a.reduce(function(x, y) {
return x> y ? x : y;
});
console.log( max );
3. 遍历方法
var a = [3, 2, 1];
function getMax(a) {
var max = a[0];
for(var i=1; i<a.length; i++) {
if(a[i]>max) max = a[i];
}
return max;
}
console.log( getMax(a) )