js获取数组最大值或最小值

数组对象arr中属性num最大值最小值

// 最大值 

Math.max.apply(Math,arr.map(item => { return item.num }))

arr.sort((a, b) => { return b-a })[0].num

// 最小值 
Math.min.apply(Math,arr.map(item => { return item.num }))

arr.sort((a, b) => { return a-b })[0].num

数组中最大值最小值

Array.max = function ( array ){
return Math.max.apply( Math, array );
};
Array.min = function ( array ){
return Math.min.apply( Math, array );
};
 
Array.prototype.max = function (){
return Math.max.apply({}, this )
}
Array.prototype.min = function (){
return Math.min.apply({}, this )
}
[1,2,3].max() // => 3
[1,2,3].min() // => 1
 
var a=[1,2,3,5];
alert(Math.max.apply( null , a)); //最大值
alert(Math.min.apply( null , a)); //最小值
 
多维数组
var a=[1,2,3,[5,6],[1,4,8]];
var ta=a.join( "," ).split( "," ); //转化为一维数组
alert(Math.max.apply( null ,ta)); //最大值
alert(Math.min.apply( null ,ta)); //最小值

猜你喜欢

转载自www.cnblogs.com/mary-123/p/11864460.html
今日推荐