javascript求数组最大值和最小值(两种方法)

版权声明:转载需注明来源 https://blog.csdn.net/Xiao_Spring/article/details/79198433

需求

返回一个数字数组的最大值或最小值

输入:一个数字数组
输出:该数组的最大值或最小值

代码

/*
    传入一个数组 获取最大或最小值
*/

const max_1 = arr=>Math.max(...arr);
const min_1 = arr=>Math.min(...arr);

Array.prototype.max_2 = function(){ 
return Math.max.apply({},this) 
};

Array.prototype.min_2 = function(){ 
return Math.min.apply({},this) 
};


const a = [11,1,34,5,8,45,12,44,54];

/*方法1*/
console.log('第一种计算最大值的方式:'+max_1(a));
console.log('第一种计算最小值的方式:'+min_1(a));

/*方法2*/
console.log('第二种计算最大值的方式:'+a.max_2());
console.log('第二种计算最小值的方式:'+a.min_2());

效果

这里写图片描述

一点思路

第一种方法是用了ES6的箭头函数以及扩展运算符 用起来特别方便
第二种方法用了Array的属性构造器,方便调用。

Github地址

https://github.com/YuanshuaiHuang/JS-/blob/master/code/20180129

猜你喜欢

转载自blog.csdn.net/Xiao_Spring/article/details/79198433