取数组中最大值

image

首先,定义一个数组:

1
const arr = [2, 6, 4, 20, -3, 8]

第一种方法

1
2
3
4
5
6
7
8
9
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)

第二种方法

1
2
3
4
const max02 = arr.sort((a, b) => {
return b-a // a-b是从小到大,b-a是从大到小
})[0]
console.log(max02)

第三种方法

1
2
const max03 = Math.max.apply(null, arr)
console.log(max03)

第四种方法

1
2
const max04 = Math.max(...arr)
console.log(max04)

第五种方法

1
2
const max05 = eval('Math.max(' + arr + ')')
console.log(max05)

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

1
2
3
4
5
6
7
'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标签。

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

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

--本文结束感谢您的阅读--