使用 for 語法模擬實現 js 數組的部份內置迭代方法

入行前端也已經快兩年了,慚愧的是最近纔開始一刷大名鼎鼎的 Professional JavaScript for Web Developers,固然,相信對於大夥,此書的中文譯做《JavaScript高級程序設計》纔算得上如雷貫耳。兩年時間並不算短,在百度和各方技術博主的加持下,有了很多 JavaScript 的知識儲備,但這些知識既多又雜、不成體系,此番看書,算是把許多零碎的知識在大腦中歸檔了。
私覺得,檢驗學習成果的最好方式,就是以本身的方式複述之。對於程序員而言,批量數據的操做是頗爲重要的技能,JavaScript 數組爲咱們提供了許多內置方法,讓咱們能夠方便地對數據進行批量操做。今天突發奇想:用 JS 如何實現數組中的那些迭代方法?對於 JS 引擎,這些方法可能會有更加高效的實現手段,可是對我而言,貌似只能經過遍歷實現了。javascript

1. Array.prototype.reverse

reverse 方法用於將數組反序,暫時只能想到經過遍歷 + 交換的方式來實現:前端

Array.prototype.fakeReverse = function fakeReverse(){
        var len = this.length - 1;
        var halfLen = len / 2;
        if(!len){
            return this
        } else {
            for(var index = 0; index <= halfLen; index++){
                var item = this[index];
                this[index] = this[len - index];
                this[len - index] = item;
            }
        }
        
        return this;
    }

2. Array.prototype.filter

filter 顧名思義,用於過濾出符合條件的數組元素,並返回一個新的數組。實現思路是建立一個新的數組,用以存儲全部經過測試的元素:java

Array.prototype.fakeFilter = function fakeFilter(callback){
        if(!(callback instanceof Function)){
            throw new Error(`Uncaught TypeError: ${callback} is not a function`)
        }
        var res = [];
        for(var index = 0; index < this.length; index++){
            if(!!callback(this[index], index, this)){
                res.push(this.index);
            }
        }
        
        return res;
    }

3. Array.prototype.map

map 方法返回將當前數組各元素映射而成的新數組。實現思路一樣是建立新數組來存儲映射後的全部元素:程序員

Array.prototype.fakeMap = function fakeMap(callback){
        if(!(callback instanceof Function)){
            throw new Error(`Uncaught TypeError: ${callback} is not a function`)
        }
        var res = [];
        for(var index = 0; index < this.length; index++){
            res.push(callback(this[index], index, this));
        }
        
        return res;
    }

4. Array.prototype.reduce

reduce 方法接受兩個參數:第一個參數爲回調函數,第二個參數爲一個「初始值」,遍歷調用此回調函數處理該初始值和當前數組元素,返回的值將做爲下一次處理的「初始值」:算法

Array.prototype.fakeReduce = function fakeReduce(callback, initVal){
        if(!(callback instanceof Function)){
            throw new Error(`Uncaught TypeError: ${callback} is not a function`)
        }
        
        let curVal = initVal;
        
        for(var index = 0; index < this.length; index++){
            initVal = callback(initVal, this[index], index, this);
        }
        
        return initVal;
    }

5. Array.prototype.forEach

forEach 方法用於遍歷數組中的每個元素:數組

Array.prototype.fakeEach = function fakeEach(callback){
        if(!(callback instanceof Function)){
            throw new Error(`Uncaught TypeError: ${callback} is not a function`)
        }
        
        for(var index = 0; index < this.length; index++){
            callback(this[index], index, this);
        }
    }

這裏只寫了寥寥幾個數組方法,原本想把 Array.prototype.sort 也實現一個的,不過排序方法那麼多,優化技巧也很多,因此打算先研究一番,有時間再專門寫一篇數組排序方法的文章。以上各代碼在實際項目中可能用不到,但自定義的排序方法則可能排上用場,由於針對不一樣場景選擇排序算法,能夠有效提升程序的運行效率。函數

相關文章
相關標籤/搜索