由于max()里面参数不能为数组,所以这里我们在Array原型对象下,对max()方法进行扩展
const arr=[1,2,3]
Array.prototype.max=function(){
return Math.max(...this)
}
console.log(arr.max())
//扩展求最小值函数,则 return Math.min(...this)
//其中...为ES6中的扩展运算符,this指向的是调用该方法的数组对象
//使用扩展运算符后
如这里 Math.max(...arr)等价于Math.max(1,2,3)
扩展数组求和方法(思路类似)
Array.prototype.sum=function(){
return this.reduce((prev,item)=>prev+item,0)
}
const arr=[1,2,3]
console.log(arr.sum())
应对自己一些经常遇到的需求,进行相应函数的封装可以提升自己的编码速度