js获取数组的最大值和最小值代码实例

吐槽君 分类:实例代码

获取数组中的最大值和最小值这个需求还是非常多的。

下面就通过代码实例介绍一下javascript是如何实现此功能。

我们可以通过prototype原型来扩展两个方法:

一.获取最大值:

Array.prototype.max = function() {
  var max = this[0];
  var len = this.length;
  for (var index = 1; index < len; index++) {
    if (this[index] > max) {
      max = this[index];
    }
  }
  return max;
}
 
Array.prototype.min = function() {
  var min = this[0];
  var len = this.length;
  for (var index = 1; index < len; index++) {
    if (this[index] < min) {
      min = this[index];
    }
  }
  return min;
}
console.log([1,2,3].max());
console.log([1,2,3].min());

上面的代码实现了我们的要求,原理极其的简单。

无非是通过遍历,挨个比较元素,最终得出最大值或者最小值。

不过上面的代码还是有点风险的,那就是,我们使用的其他库可能也是用同样的名称来修改原型。

所以我们需要进行以下判断,代码如下:

if(typeof Array.prototype['max'] == 'undefined') {
  Array.prototype.max = function () {
    //code
  }
}

其实上面的实现方式并不是太理想,还有更为简便的方式。

代码实例如下:

Array.prototype.max = function () {
  return Math.max.apply({}, this)
}
Array.prototype.min = function () {
  return Math.min.apply({}, this)
}
console.log([1, 2, 3].max());
console.log([1, 2, 3].min())

相关阅读:

(1).prototype属性可以参阅javascript prototype原型一章节。

(2).Math.max()方法可以参阅Math.max()一章节。

(3).Math.min()方法可以参阅Math.min()一章节。

(4).apply()方法可以参阅js apply()一章节。

js获取数组的最大值和最小值代码实例,这样的场景在实际项目中还是用的比较多的,关于js获取数组的最大值和最小值代码实例就介绍到这了。

js获取数组的最大值和最小值代码实例属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容