# 前端覆盤專題(三)--數組方法及手寫實現

類數組結構

1.只包含使用從零開始,且天然遞增的整數作鍵名 2.定義了length表示元素個數html

建立數組

1.Array.of()

Array.of(element0[, element1[, ...[, elementN]]])數組

做用: 將一組參數轉換爲數組實例markdown

參數: elementN:任意個參數,將按順序成爲返回數組中的元素。函數

// 建立數組的方法
        // Array.of(一組參數) -- 將一組參數轉換爲數組實例
        Array._of = function (...args) {
           
            return args
        }
複製代碼

2.Array.from()

Array.from(arrayLike[, mapFn[, thisArg]])oop

做用: 將類數組對象/可迭代對象轉換爲數組實例測試

參數:ui

arrayLike:想要轉換成真實數組的類數組對象或可遍歷對象。this

mapFn:可選參數,若是指定了該參數,則最後生成的數組會通過該函數的加工處理後再返回。spa

thisArg:可選參數,執行 mapFn 函數時 this 的值。prototype

// 建立數組的方法
        // Array.form(類數組對象/可迭代對象) -- 將類數組對象/可迭代對象轉換爲數組實例
        // Array.from(arrayLike[, mapFn[, thisArg]])
        Array._from = function (object, mapfunction, thisvalue) {
            let objThis = thisvalue || this
            let result = []
            // 沒有length屬性或length爲0的直接返回空數組
            if (!object.length) {
                return result
            }
            if (typeof object === 'string') {
                return object.split('')
            } else if (object instanceof  Array) {
                object.forEach(item => {
                    result.push(item)
                })
            } else {
                Object.keys(object).forEach(key => {
                    if (key != 'length') {
                        result.push(object[key])
                    }
                })
            }
            if ( (typeof mapfunction !== 'function') && ( typeof mapfunction !== 'undefined' )) {
                throw new TypeError ( mapfunction + 'is not a function' )
            }
            if ((typeof mapfunction !== 'undefined')) {
                return result.map(mapfunction, objThis)
            }
            return result
        }

        // 類數組測試
         const eg1 = Array._from({0:0,1:1,2:2,3:4,5:'aa',length:2})
         console.log(eg1);
        // 字符串測試
         const eg3 = Array._from('asiwdygyqw')
         console.log(eg3);
        // 數組測試
         const eg22 = Array._from([1,2,3,9,8,7], x=> x*100)
         console.log(eg22);
複製代碼

改變原數組的方法

1. arrayObject.splice()

arrayObject.splice(index,howmany,item1,.....,itemX)

image.png

功能:

刪除--傳入兩個參數:開始位置、刪除數量

插入--傳入三個參數:開始位置、0(要刪除的元素數量)、要插入的任意多個元素

替換--傳入三個參數:開始位置、要刪除的元素數量、要插入的任意多個元素

Array.prototype._splice = function (index, howmany) {
            let arr = this
            // 截取位置以前的數組
            let beforeArr = arr.slice(0, index)
            // 截取位置以後的數組
            let afterArr = arr.slice(index+howmany, arr.length)
            // 截取添加的參數
            let subArr = Array.prototype.slice.call(arguments, 2)
            // 被截取的數組
            let returnArr = arr.slice(index,index+howmany)
            let result = []
            result = [...beforeArr,...subArr,...afterArr]
            // 改變原數組
            for (let i=0;i<result.length;i++) {
                this[i] = result[i]
            }
            if (this.length-result.length) {
                this.splice(result.length,this.length-result.length)
            }
            // 返回被截取的數組
            return returnArr

        }
複製代碼

Array.prototype.slice.call()方法詳解: www.cnblogs.com/jing-tian/p…

2. arrayObject.sort()

image.png

// arrayObject.sort()
        Array.prototype._sort = function (func) {
            let arr = this
            // 若是數組長度小於等於1直接返回原數組
            if (arr.length<=1) {
                return arr
            }
            // 若是沒有函數參數
            if (func == undefined) {
                // 冒泡排序,兩層循環,外層控制趟數,內層控制每趟比較次數
                for (let i=0;i<arr.length;i++) {
                    for(let j=0;j<arr.length-i-1;j++) {
                        let temp = ""
                        if(String(arr[j])>String(arr[j+1])) {
                            temp = arr[j+1]
                            arr[j+1] = arr[j]
                            arr[j] = temp
                        }
                    }
                }
            } else if (typeof func == 'function') {
                for(let i=0;i<arr.length;i++) {
                    for (let j=0;j<arr.length-i-1;j++){
                        let flag = func(arr[j],arr[j+1])
                        if(flag>0){
                            // 這也是一種交換方式
                            arr[j] = arr[j] +arr[j+1]
                            arr[j+1] = arr[j] - arr[j+1]
                            arr[j] = arr[j] - arr[j+1]
                        }
                    }
                }
            } else {
                throw new TypeError (func + ' is not a function')
            }
            return arr
        }
        const arr1 = [1,5,4,1,5,3,7]
        arr1._sort((a,b) => b-a)
        console.log(arr1);
複製代碼

3. arrayObject.pop()

image.png

// arrayobject.pop()
        Array.prototype._pop = function () {
            let arr = this
            // 若是數組爲空返回undefined
            if (arr.length == 0) {
                return undefined
            }
            let result = arr[arr.length-1]
            this.length = this.length-1
            return result
        }
        const arr1 = [1,55,7,88]
        console.log(arr1._pop());
複製代碼

4. arrayObject.shift()

image.png

// arrayObject.shift()
        Array.prototype._shift = function () {
            let arr = this
            if (arr.length == 0) {
                return 
            }
            let result = arr[0]
            this.splice(0,1)
            return result
        }
        let arr1 = [1,2,3]
        console.log(arr1._shift());
複製代碼

5. arrayObject.unshift()

image.png

// arrayObject.unshift()
        Array.prototype._unshift = function () {
            let arr = this
            let beforeArr = []
            Array.prototype.forEach.call(arguments,item => {
                beforeArr[beforeArr.length] = item
            })
            arr = [...beforeArr,...arr]
            console.log(arr);
            arr.forEach((item,index) => {
                this[index] = arr[index]
            })
            console.log(this);
            return this.length
        }
        let arr1 = [1,2,3,4,5,6,7]
        console.log(arr1._unshift(6,8,9,44));
複製代碼

6. arrayObject.push()

image.png

// arrayObject.push() 
        Array.prototype._push = function () {
            Array.prototype.forEach.call(arguments, item => {
                this[this.length] = item
            })
            console.log(this);
            return this.length
        }
        let arr1 = [1,2,3,4,5]
        console.log(arr1._push(55,44,66));
複製代碼

7. arrayObject.reverse()

image.png

// arrayObject.reserve()
        Array.prototype._reserve = function () {
            for (let i=0;i<this.length/2;i++) {
                let temp = this[this.length-1-i]
                this[this.length-1-i] = this[i]
                this[i] = temp
            }
        }
        let arr1 = [1,2,3,4,5]
        arr1._reserve()
        console.log(arr1);
複製代碼

8. arrayObject.fill()

image.png

Array.prototype._fill = function (val, start=0, end) {
            let arr = this
            let len = arr && arr.length || 0
            end = end || len
            start = start < 0 ? 0 : start // 設置循環開始值
            end = end>len ? len : end // 設置循環結束值
            for(; start<end;start++) {
                arr[start] = val
            }
            return arr
        }
        let arr1 = [1,2,3]
        console.log(arr1._fill(7,0,2));
        console.log(arr1);
複製代碼

不改變原數組的方法

1. arrayObject.slice()

image.png

Array.prototype._slice = function (start, end) {
            let arr = this
            start = start < 0 ? arr.length+start :start
            end = end && (end < 0 ? arr.length+end : end) || arr.length
            let result = []
            for (; start<end;start++) {
                result.push(arr[start])
            }
            return result
        }
        let arr1 = [1,2,3,4]
        console.log(arr1._slice(0,1));
複製代碼

2. arrayObject.join()

image.png

Array.prototype._join = function (str) {
            let arr = this
            str = str ? str : ""
            let result = ""
            for (let i=0;i<arr.length-1;i++) {
                result = result+arr[i]+str
            }
            result = result+arr[arr.length-1]
            return String(result)
        }
        let arr1 = [1,2,3,4]
        console.log(arr1._join('$'));
複製代碼

3. arrayObject.toLocalString()

image.png

Array.prototype._tolocalString = function () {
            let arr = this
            return  arr.join(',')
        }
        let arr1 = [1,2,3,4]
        console.log(arr1._tolocalString());
複製代碼

4. arrayObject.toString()

5. arrayObject.conat()

image.png

Array.prototype._concat = function () {
            let arr = this
            let result = arr
            Array.prototype.forEach.call(arguments, item => {
                if (item instanceof Array) {
                    result = [...result, ...item]
                } else {
                    result = [...result, item]
                }
                
            })
            return result
        }
        let arr1 = [1,12,55,6,8]
        console.log(arr1._concat(1,[5,5,6,[7]],8));
        console.log(arr1 instanceof Array);
複製代碼

6. arrayObject.indexOf()

image.png

Array.prototype._indexOf = function (str, start=0) {
            let arr = this
            let result = -1
            for (; start<arr.length;start++) {
                if(str === arr[start]) {
                    result = start
                }
            }
            return result
        }
        let arr1 = [1,2,3,4,5]
        console.log(arr1._indexOf(1));
複製代碼

7. arrayObject.lastIndexOf()

image.png

Array.prototype._lastIndexOf = function (str, lastIndex) {
            let arr = this
            let result = -1
            lastIndex = lastIndex || arr.length-1
            while (lastIndex < 0) {
                lastIndex =  lastIndex+arr.length
            }
            if (lastIndex>arr.length) {
                return result  
            }
            for (; lastIndex >= 0; lastIndex--) {
                if (str === arr[lastIndex]) {
                    result = lastIndex
                }
            }
            return result

        }
        let arr1 = [1,2,3,4,5,6]
        console.log(arr1._lastIndexOf(1,3));
複製代碼

8. arrayObject.includes()

image.png includes方法是爲了彌補indexOf方法的缺陷而出現的:

1.indexOf方法不能識別NaN

2.indexOf方法檢查是否包含某個值不夠語義化,須要判斷是否不等於-1,表達不夠直觀

Array.prototype._includes =  function (str, start=0) {
            let arr = this
            if (start>=arr.length||!arr.length) {
                return false
            }
            for (; start<arr.length;start++) {
                if (str === arr[start]) {
                    return true
                }
            }
            return false

        }
        let arr1 = [1,2,3,4,'a']
        console.log(arr1._includes(4,0));
複製代碼

遍歷方法

1. arrayObject.forEach()

image.png

Array.prototype._forEach = function (func, thisArr) {
            let arr = thisArr || this
            if (typeof func !== 'function') {
                throw new Error (func + 'is not a function')
            }
            for (let i=0; i < arr.length; i++) {
                func.call(arr,arr[i],i,arr)
            }
        }

        let arr1 = [1,2,3,4,5]
        console.log(arr1._forEach(item=>console.log(item)));
複製代碼

2. arrayObject.every()

檢測數組全部元素是否都符合判斷條件

every() 方法用於檢測數組全部元素是否都符合指定條件(經過函數提供)。

every() 方法使用指定函數檢測數組中的全部元素:

若是數組中檢測到有一個元素不知足,則整個表達式返回 false ,且剩餘的元素不會再進行檢測。

若是全部元素都知足條件,則返回 true。

注意: every() 對空數組檢測 返回 true。

注意: every() 不會改變原始數組。

image.png

Array.prototype._every = function (func, thisValue) {
            let arr = thisValue || this
            if (typeof func !== 'function') {
                throw new TypeError(func + 'is not a function')
            }
            if (arr.length == 0) {
                return true
            }
            for (let i=0; i<arr.length; i++) {
               if(! func.call(arr,arr[i],i,arr) ) {
                   return false
               }
           }
           return true
        }
        function checkAdult(item) {
            return item >= 11
        }
 
        let arr = [32, 33, 16, 40]
        let result = arr._every(checkAdult)
        console.log(result) // true
複製代碼

3. arrayObject.some()

image.png

image.png

Array.prototype._some = function (func, thisValue) {
            let arr = thisValue || this
            if (typeof func !== 'function') {
                throw new TypeError (func + 'is not a function')
            }
            if (arr.length == 0) {
                return true
            }
            for (let i=0; i<arr.length; i++) {
                if (func.call(arr, arr[i], i, arr)) {
                    return true
                }
            }
            return false
        }
        let arr1 = [1,2,3,88]
        console.log(arr1._some(item=> item>100));
複製代碼

4. arrayObject.filter

image.png

image.png

Array.prototype._filter = function (func, thisValue) {
            let arr = thisValue || this
            let result = []
            if (typeof func !== 'function') {
                throw new TypeError (func + 'is not a function')
            }
            if (arr.length == 0) {
                return result
            }
            for (let i=0; i<arr.length; i++) {
                if(func.call(arr, arr[i], i, arr)) {
                    result.push(arr[i])
                }
                
            }
            return result
        }
        let arr1 = [1,2,3,4,5,6]
        console.log(arr1._filter(item=>item>1));
複製代碼

5. arrayObject._map()

image.png

image.png

Array.prototype._map = function (func, thisValue) {
            let arr = thisValue || this
            let result = []
            if (typeof func !== 'function') {
                throw new TypeError (func + 'is not a function')
            }
            if (!arr.length) {
                return result
            }
            for (let i=0; i<arr.length; i++) {
                arr[i] = func.call(arr, arr[i], i, arr)
            }
            return arr

        }
        let arr1 = [1,2,3,4,5,6]
        console.log(arr1._map(item=>item*10));
複製代碼

5. arrayObject.reduce()

image.png

image.png

Array.prototype._reduce = function (func, initValue=0) {
            let arr= this
            let result = initValue
            if (typeof func !== 'function') {
                throw new TypeError (func + 'is not a function') 
            }
            if (!arr.length) {
                return []
            }
            for (let i=0; i<arr.length; i++) {
                result = func.call(arr, result, arr[i], i, arr)
            }
            return result
        }
        let arr1 = [1,2,30]
        console.log(arr1._reduce((total,item,i,arr)=> item+total));
複製代碼

6. arrayObject.find()

image.png

image.png

Array.prototype._find = function (func, thisValue) {
            let arr = thisValue || this
            if (typeof func != 'function') {
                throw new TypeError (func + 'is not a function')
            }
            if (!arr.length) {
                return undefined
            }
            for (let i=0; i< arr.length; i++) {
                if (func.call(arr, arr[i], i, arr)) {
                    return arr[i]
                }
            }
            return undefined

        }
        let arr1 = [1,2,3,44,55]
        console.log(arr1._find(item => (item>10)));
複製代碼

7. arrayObject.findIndex()

image.png

Array.prototype._find = function (func, thisValue) {
            let arr = thisValue || this
            if (typeof func != 'function') {
                throw new TypeError (func + 'is not a function')
            }
            if (!arr.length) {
                return -1
            }
            for (let i=0; i< arr.length; i++) {
                if (func.call(arr, arr[i], i, arr)) {
                    return i
                }
            }
            return -1

        }
        let arr1 = [1,2,3,44,55]
        console.log(arr1._find(item => (item>10)));
複製代碼
相關文章
相關標籤/搜索