JS高级之给数组扩展方法

一、给数组扩展方法

例如:数组有没有一个求最大值的方法?没有

需求:给数组加一个 max 方法,可以求出数组里的最大数,并且要让每个数组都有这个方法

1、如何给数组扩展方法

原理:给数组(Array)对象添加一个原型对象名叫max,并且给这个叫max的原型对象设置一个方法。

但是方法里操作的数据不能写死,而应该谁调用就用谁的数据,所以也就是说要用 this

Array.prototype.max = function () {
            // console.log(max方法, this)
            // 先取出调用这个方法的数组里的第一个元素
            let max = this[0]
            for (let i = 1; i < this.length; i++) {

                if (this[i] > max) {
                    max = this[i]
                }
            }
            // 把最大值返回
            return max
        }

这样,就在Array里设置好了一个叫max的原型对象,由于所有数组都属于Array对象,所以,任意一个数组都能通过原型链的方式找到这个叫max的原型对象,并调用该方法

Array.prototype.max = function () {
            // console.log(max方法, this)
            // 先取出调用这个方法的数组里的第一个元素
            let max = this[0]
            for (let i = 1; i < this.length; i++) {

                if (this[i] > max) {
                    max = this[i]
                }
            }
            // 把最大值返回
            return max
        }
        let arr1 = [10, 20, 30]
        let arr2 = [100, 200, 300]

        let res1 = arr1.max()
        let res2 = arr2.max()

        console.log(res1)
        console.log(res2)
经验分享 程序员 微信小程序 职场和发展