模拟 Array的一些内置方法

  开始学习 Vue后,使用了一些之前学过的 Array的自带方法.这些方法之前只是留了个印象,在当时看来,所需要的参数相当奇怪,完全不懂为什么这么写,在对回调函数有了一定的理解之后,就感觉比较清晰了.为了增强印象,今天把这些方法用自己的想法模拟一下.

  1.   Array.prototype.find  
1     Array.prototype._findIndex = function (callback) {
2         for (var i = 0; i < this.length; i++) {
3             if (callback(this[i],i)) {
4                 return this[i];
5             }
6         }
7     }

  2.  Array.prototype.findIndex

    Array.prototype._findIndex = function (callback) {
        for (var i = 0; i < this.length; i++) {
            if (callback(this[i],i)) {
                return i;
            }
        }
    }

  3.  Array.prototype.filter

    Array.prototype._filter = function (callback) {
        var newArr = [];
        for (var i = 0; i < this.length; i++) {
            if (callback(this[i],i)) {
                newArr.push(this[i])
            }
        }
        return newArr
    }

  4.  Array.prototype.every

    Array.prototype._every=function(callback){
        for(var i =0;i<this.length;i++){
            if(!callback(this[i],i)){
                return false
            }
        }
        return true
    }

  5.  Array.prototype.some

    Array.prototype._some=function(callback){
        for(var i =0; i<this.length;i++){
            if(callback(this[i],i)){
                return true
            }
        }
        return false
    }

  6.  Array.prototype.map

1     Array.prototype._map=function(callback){
2         for(var i =0;i<this.length;i++){
3             this[i]=callback(this[i],i)
4         }
5         return this;
6     }

  7.  Array.prototype.forEach

    Array.prototype._forEach=function(callback){
        for(var i =0;i<this.length;i++){
            callback(this[i],i,this)
        }
    }

  8.  Array.prototype.sort

     用冒泡排序模拟

    Array.prototype._sort = function (callback) {
     if (!this || !this.length) return [];
if (this.length === 1) return this; for (var i = 0; i < this.length - 1; i++) { if (callback(this[i], this[i + 1]) > 0) { var temp = this[i]; this[i] = this[i + 1]; this[i + 1] = temp } } var last = this.pop() return this._sort(callback).concat(last) }

    

  以上内置方法,全部带有隐式迭代.在需要遍历数组进行操作时,尽量转化为以上方法的使用,而不是自己写循环,执行效率会提高不少.

猜你喜欢

转载自www.cnblogs.com/mugun/p/10693235.html