码迷,mamicode.com
首页 > 编程语言 > 详细

求数组最大值或最小值

时间:2018-08-14 21:09:23      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:const   取出   log   接收   ons   console   min   直接   his   

1. 一维数组

const arr = [1, 5, 9, 0, 11]
const maxValue = Math.max.apply(null, arr )
const minValue = Math.min.apply(null, arr )
console.log(maxValue ,minValue)

 

2. 多维数组

const arr1 = [2, 5, 8]
const arr2 = [9, 5, 2]
const convertArr = arr1.join(‘,‘).split(‘,‘)   // 转为一维数组
const maxValue = Math.max.apply(null, convertArr)
const minValue = Math.min.apply(null, convertArr)

解释一下为什么可以通过apply这种方式来求最值,这是因为 

Math.max() 或  Math.min()方法不能接收一个数组为参数,我们要想直接求最值,只能这样用:
const arr = Math.max(1, 5, 8, 2)
console.log(arr)

所以我们就要把数组里面的值一一取出来,这时就可以利用apply的特性,即接受数组为 非第一个参数, 再把原本的第一个this指向的参数置为null,就可以了

求数组最大值或最小值

标签:const   取出   log   接收   ons   console   min   直接   his   

原文地址:https://www.cnblogs.com/aloehui/p/9477432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!