JavaScript获取数组中最大(最小)值
2017-08-10 17:44
507 查看
思路:
将数组第一个元素当做最大(最小)值,存入变量;
遍历数组,依次与此变量比较,若大于(小于)变量,将此元素当做最大(最小)值存入变量;
返回此变量;
测试如下
用forEach()方法改写上面的代码:(for循环性能要比forEach()差)
用reduce()方法改写上面的代码:
reduce()方法可以接收一个回调函数callbackfn,可以在这个回调函数中拿数组中的初始值(preValue)与数组中当前被处理的数组项(curValue)做比较,如果preValue大于curValue值返回preValue,反之返回curValue值
用Math 对象的Math.max()和Math.min()方法:
(完)
将数组第一个元素当做最大(最小)值,存入变量;
遍历数组,依次与此变量比较,若大于(小于)变量,将此元素当做最大(最小)值存入变量;
返回此变量;
var arr = [1, 45, 23, 3, 6, 2, 7, 234, 56];
//最大值 Array.prototype.max = function() { var max = this[0]; var len = this.length; for (var i = 1; i < len; i++) { if (this[i] > max) { max = this[i]; } } return max; } //最小值 Array.prototype.min = function() { var min = this[0]; var len = this.length; for (var i = 1; i < len; i++) { if (this[i] < min) { min = this[i]; } } return min; }
测试如下
console.log(arr.max()); //234 console.log(arr.min()); //1
用forEach()方法改写上面的代码:(for循环性能要比forEach()差)
Array.prototype.max = function (){ var max = this[0]; this.forEach (function(ele,index,arr){ if(ele > max) { max = ele; } }) return max; } Array.prototype.min = function (){ var min = this[0]; this.forEach (function(ele,index,arr){ if(ele < min) { min = ele; } }) return min; }
用reduce()方法改写上面的代码:
reduce()方法可以接收一个回调函数callbackfn,可以在这个回调函数中拿数组中的初始值(preValue)与数组中当前被处理的数组项(curValue)做比较,如果preValue大于curValue值返回preValue,反之返回curValue值
Array.prototype.max = function() { return this.reduce(function(preValue, curValue,index,array) { return preValue < curValue ? curValue : preValue; }) } Array.prototype.min = function() { return this.reduce(function(preValue, curValue,index,array) { return preValue > curValue ? curValue : preValue; }) }
用Math 对象的Math.max()和Math.min()方法:
Array.prototype.max = function () { return Math.max.apply({},this); } Array.prototype.min = function () { return Math.min.apply({},this); }
(完)
相关文章推荐
- JavaScript获取数组最小值和最大值的方法
- JavaScript 获取数组中最大值、最小值
- Javascript中获取数组最大值和最小值的方法
- Javascript中获取数组最大值和最小值以及最大值和最小值的下标 没学对象前的最简单最基本的方法
- Javascript获取数组中的最大值和最小值方法汇总
- JavaScript获取数组最大值和最小值
- Javascript获取数组中的最大值和最小值的方法汇总
- Javascript获取数组中的最大值和最小值的方法汇总
- javascript的原生方法获取数组中的最大(最小)值
- Javascript中获取数组最大值和最小值的方法
- JavaScript如何获取数组最大值和最小值
- Javascript获取数组中最大值和最小值
- JavaScript获取数组最小值和最大值的方法
- Javascript获取数组中的最大值和最小值的方法汇总
- javascript的原生方法获取数组中的最大(最小)值
- JavaScript获取数组中的最大值和最小值
- JavaScript获取数组最小值和最大值的方法
- JavaScript获取数组最大值和最小值
- PHP里获取一维数组里的最大值和最小值
- C#控制台基础 获取一维int类型数组的最大值,最小值