取数组中最大值

首先,定义一个数组:

const arr = [2, 6, 4, 20, -3, 8]
第一种方法
Array.prototype.max = function() {
  let max = this[0]
  this.forEach(item => {
    max = max >= item ? max : item
  })
  return max
}
const max01 = arr.max()
console.log(max01)
第二种方法
const max02 = arr.sort((a, b) => {
  return b-a // a-b是从小到大,b-a是从大到小
})[0]
console.log(max02)
第三种方法
const max03 = Math.max.apply(null, arr)
console.log(max03)
第四种方法
const max04 = Math.max(...arr)
console.log(max04)
第五种方法
const max05 = eval('Math.max(' + arr + ')')
console.log(max05)

最后这个比较难理解,涉及到隐式类型转换和eval的用法。
首先,进行隐式转换

'Math.max(' + arr + ')''
// 相当于
'Math.max(' + arr.toString() + ')'
// 相当于
'Math.max(' + '2, 6, 4, 20, -3, 8' + ')'
// 相当于
'Math.max(2, 6, 4, 20, -3, 8)'

然后就是eval的用法

eval() 函数可计算某个字符串,并执行其中的的 JavaScript 代码。

语法:
eval(string)

string必需。要计算的字符串,其中含有要计算的 JavaScript 表达式或要执行的语句。该方法只接受原始字符串作为参数,如果 string 参数不是原始字符串,那么该方法将不作任何改变地返回。因此请不要为 eval() 函数传递 String 对象来作为参数。

简单来说吧,就是用JavaScript的解析引擎来解析这一堆字符串里面的内容,这么说吧,你可以这么理解,你把eval看成是script标签。

eval('Math.max(2, 6, 4, 20, -3, 8)')
// 相当于
<script>
    Math.max(2, 6, 4, 20, -3, 8)
</script>

如有问题,欢迎指正!!!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值