javascript 找出数组的最大值和最小值的方法 (6种方法)


要有遥不可及的梦想,也要有脚踏实地的本事。----------- Grapefruit.Banuit Gang(香柚帮)


求数组的最大值和最小值,方法还是挺多的,我会一一列举出来:

     //首先我们声明一个不规则的数字数组
     var arr = [1,7,3,1,5,8,9,0,15,10,6,5];

     //第一种方法:

     // 最小值
     Array.prototype.min = function () {
         let min = this[0];
         let len = this.length;
         for (let i = 1; i < len; i++) {
             if (this[i] < min) min = this[i]
         }
         return min
     }
     // 最大值
     Array.prototype.max = function () {
         let max = this[0];
         let len = this.length;
         for (let i = 1; i < len; i++) {
             if (this[i] > max) max = this[i]
         }
         return max
     }
	 // 结果
     console.log(arr.min()); // 0
     console.log(arr.max()); // 15

     //第二种方法:

     // 最小值
     Array.min = function(array) {
         return Math.min.apply(Math, array)
     }
     // 最大值
     Array.max = function (array) {
         return Math.max.apply(Math, array)
     }
	 // 结果
     console.log(Array.min(arr)); // 0
     console.log(Array.max(arr)); // 15

     //第三种方法:

     // 最小值
     Array.prototype.min = function() {
         return Math.min.apply({}, this)
     }
     // 最大值
     Array.prototype.max = function () {
         return Math.max.apply({}, this)
     }
     // 结果
     console.log(arr.min()); // 0
     console.log(arr.max()); // 15

     //第四种方法:

     // 最小值
     Array.prototype.min = function () {
         return this.reduce((pre, cur) => {
             return pre < cur ? pre : cur
         })
     }
     // 最大值
     Array.prototype.max = function () {
         return this.reduce((pre, cur) => {
             return pre > cur ? pre : cur
         })
     }
     // 结果
     console.log(arr.min()); // 0
     console.log(arr.max()); // 15

     //第五种方法:

     let sortArr = arr.sort((a, b) => a - b)
     // 最小值
     sortArr[0]
     // 最大值
     sortArr[sortArr.length - 1]
     // 结果
     console.log(sortArr[0]); // 0
     console.log(sortArr[sortArr.length - 1]); // 15

     //第六种方法:

     // 最小值
     Math.min(...arr)
     // 最大值
     Math.max(...arr)
     // 结果
     console.log(Math.min(...arr)); // 0	
     console.log(Math.max(...arr)); // 15

就是这六种方法,已经全部列举出来了,希望能帮助到你吧!!!

  • 8
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@Grapefruit

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值