相信有小伙伴看到這一個標題可能會想:現在都可以自己寫方法了嗎?這么炸裂。沒錯我們是可以自己寫方法的。
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
感謝大家的閱讀,如有不對的地方,可以向我指出,感謝大家!