相信有小伙伴看到这一个标题可能会想:现在都可以自己写方法了吗?这么炸裂。没错我们是可以自己写方法的。
1.我们定义的这个方法,任何一个数组实例对象都可以使用
2.自定义的方法写到 数组.propertype身上
最大值
const arr = [1,2,3,4]Array.prototype.max = function() {// 这里我们需要运用到展开运算符// 原型里的this指向实例对象 arrreturn Math.max(...this)}// 方法定义成功console.log(arr.max())//4
最小值
const arr = [1,2,3,4]Array.prototype.min = function() {// 这里我们需要运用到展开运算符// 原型里的this指向实例对象 arrreturn Math.min(...this)}// 方法定义成功console.log(arr.min())//1
求和
const arr = [1,2,3,4]Array.prototype.sum = function() {// this指向实例对象return this.reduce((prev,item)=>prev + item,0)}console.log(arr.sum()) //10
感谢大家的阅读,如有不对的地方,可以向我指出,感谢大家!