前言  在数组中并没有提供arr.max()arr.min()这样的方法。那么是不是可以通过别的方式实现类似这样的方法呢?那么今天我们就来整理取出数组中最大值和最小值的一些方法。
 
法一:其实利用 ECMAScript5的 ...展开运算符可以很简单的解决这个问题
var arr=[,,,,,];
Math.max(...arr); //
Math.min(...arr); //
 法二 : 对数组进行遍历
对于数组的遍历,有多种不同的方法,下面对各种方法进行比较:Array.prototype.max=function(){


Array.prototype.max=function(){
let max=this[];
this.forEach(function(item,index){
if(item>max){
max=item;
}
});
return max;
}
var arr = [,,,,,,,,,,,];
console.time("费时");
console.log(arr.max()); //
console.timeEnd("费时"); // 费时:0.376ms
// ================================================ //
Array.prototype.max=function(){
let max=this[];
this.map(function(item,index){
if(item>max){
max=item;
}
});
return max;
}
var arr = [,,,,,,,,,,,];
console.time("费时");
console.log(arr.max()); //
console.timeEnd("费时"); // 费时: 0.402ms // ================================================= //
Array.prototype.max=function(){
let max=this[];
for(var i=;i<this.length;i++){
if(this[i]>max){
max=this[i];
}
}
return max;
}
var arr = [,,,,,,,,,,,];
console.time("费时");
console.log(arr.max()); //
console.timeEnd("费时"); // 费时: 0.522ms
  我们来看看如果数组中不全是数值的会是怎样的?
var arr = [1,45,23,3,6,2,7,234,56,'2345',5,'a',1000];
arr.max(); // "a"
['a',1000,'c'].max(); // "c"
[1000,'a'].max(); //
  咦,结果好像不是我们想要的,经过测试,我觉得数值和字符的大小比较是一下的规则:
    ① 如果两个数都是数值的时候,按照普通的数值比较方法
    ② 如果两个数都是字符串,则两个字符串从高位逐位开始比较,根据ASCLL码的大小比较;
      英文字母>数字,小写字母>大写字母 
    【注】字符转ascii码:用charCodeAt();
  1. "A".charCodeAt(); //
    "a".charCodeAt(); //
    ③ 如果一个是字符串,一个是数值,则将数值转换为字符串,按照两个字符串的大小比较方法比较
 
法三: 还可以使用Array.prototype.reduce 方法进行遍历,使用此法,无需添加额外的 max 变量
Array.prototype.max=function(){

  return arr.reduce(function(prev,next){
return prev>next?prev:next;
});
}
var arr = [1,45,23,3,6,2,7,234,56,222,34444,9];
console.time("费时");
console.log(arr.max()); //
console.timeEnd("费时"); // 费时: 0.389ms

求数组最小值的就不再多说了,同理易得~

总结

  上面求数组的最值最简单的还是法一,剩下的都是遍历数组,对于数组的遍历也要选择好方法,不同的遍历方法性能不同,其中 Array.prototype.map虽然使用起来优雅,但是实际性能并不会比forEach好,具体的还是示情况而定吧

最新文章

  1. YYModel 源码解读(二)之YYClassInfo.h (3)
  2. jquery 新闻滚动效果
  3. NSString的八条实用技巧
  4. 【nginx】配置文件的优化
  5. Mongodb--gridfs与分片实验
  6. BMP文件格式分析
  7. 转....导入excel错误:外部表不是预期的格式 解决方案
  8. Codeforces294B - Shaass and Bookshelf(贪心)
  9. Static用法
  10. TinyXml高速入口(一)
  11. iOS UITableViewCell点击时子视图背景透明的解决方法
  12. java 排序的几篇好文章
  13. day 18 - 1 正则与 re 模块
  14. bootstrap selectpicker控件select下拉框动态数据无法回显的问题
  15. Python 16 html 基础 jQuery &amp; Javascript研究
  16. Cisco交换机基础命令 + Win Server08 R2 多网卡配置链路聚合
  17. Axis2开发WebService客户端 的3种方式
  18. LeetCode--350--两个数组的交集2
  19. django的数据库操作
  20. 【java规则引擎】《Drools7.0.0.Final规则引擎教程》第4章 4.3 日历

热门文章

  1. cogs 1199选课(树形dp 背包或多叉转二叉
  2. hdu 5534 Partial Tree(完全背包)
  3. Java 网络编程:必知必会的 URL 和 URLConnection
  4. git拉取分支
  5. IDEA中输出syso的快捷键设置
  6. pandas可视化:各种图的简单使用
  7. golang时间转换
  8. 猿类如何捕获少女心--难以琢磨的try-catch
  9. android 定时提醒 - Notification
  10. html的表格边框为什么会这么粗?