# 前端复盘专题(三)–数组方法及手写实现

类数组结构

1.只包含使用从零开始,且自然递增的整数做键名
2.定义了length表示元素个数

创建数组

1.Array.of()

Array.of(element0[, element1[, …[, elementN]]])

作用: 将一组参数转换为数组实例

参数:
elementN:任意个参数,将按顺序成为返回数组中的元素。

// 创建数组的方法
        // Array.of(一组参数) -- 将一组参数转换为数组实例
        Array._of = function (...args) {
           
            return args
        }
复制代码

2.Array.from()

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

作用: 将类数组对象/可迭代对象转换为数组实例

参数:

arrayLike:想要转换成真实数组的类数组对象或可遍历对象。

mapFn:可选参数,如果指定了该参数,则最后生成的数组会经过该函数的加工处理后再返回。

thisArg:可选参数,执行 mapFn 函数时 this 的值。

// 创建数组的方法
        // 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)));
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享