[关闭]
@Wangww0925 2019-01-23T01:27:34.000000Z 字数 656 阅读 177

数组元素最大值、最小值

Array数组


原型 - 通过Math方法

数组元素最大值

  1. Array.prototype.max = function (){
  2. return Math.max.apply(null,this)
  3. }
  4. var arr = [1,50,62,85,3,9,46,12,30];
  5. console.log(arr.max()); // 85

数组元素最小值

  1. Array.prototype.min = function (){
  2. return Math.min.apply(null,this)
  3. }
  4. var arr = [1,50,62,85,3,9,46,12,30];
  5. console.log(arr.min()); // 1

原型 - 通过sort排序方法

数组元素最大值

  1. Array.prototype.max = function (){
  2. this.sort(function(a,b){
  3. return b-a;
  4. })
  5. return this[0]
  6. }
  7. var arr = [1,50,62,85,3,9,46,12,30];
  8. console.log(arr.max()); // 85

数组元素最小值

  1. Array.prototype.min = function (){
  2. this.sort(function(a,b){
  3. return a-b;
  4. })
  5. return this[0]
  6. }
  7. var arr = [1,50,62,85,3,9,46,12,30];
  8. console.log(arr.min()); // 1

作者 wendy
2019 年 1月 17日


参考文献

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注