當(dāng)前位置:首頁(yè) > IT技術(shù) > Web編程 > 正文

手寫(xiě)一個(gè)splice js
2021-09-16 11:40:54

先來(lái)介紹一下什么是splice

splice == Array.prototype.splice

如介紹,是數(shù)組通用方法

以下是介紹

定義和用法

splice() 方法向/從數(shù)組中添加/刪除項(xiàng)目,然后返回被刪除的項(xiàng)目。

注釋?zhuān)涸摲椒〞?huì)改變?cè)紨?shù)組。

語(yǔ)法

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

參數(shù) 描述
index 必需。整數(shù),規(guī)定添加/刪除項(xiàng)目的位置,使用負(fù)數(shù)可從數(shù)組結(jié)尾處規(guī)定位置。
howmany 必需。要?jiǎng)h除的項(xiàng)目數(shù)量。如果設(shè)置為 0,則不會(huì)刪除項(xiàng)目。
item1, ..., itemX 可選。向數(shù)組添加的新項(xiàng)目

現(xiàn)在獻(xiàn)上手寫(xiě)splice代碼

Array.prototype.mySplice = (function() {
    let _this

    function handlerType(value) {
        // 處理數(shù)據(jù)類(lèi)型,看是否為數(shù)字
        return /^[+-]?(0|([1-9]d*))(.d+)?$/g.test(String(value))
    }

    function handlerIndex(value) {
        function _handler(value) {
            return Math.max(0, value + _this.length)
        }
        value = ~~value
            // 處理索引,如果大于等于0取本身,反之說(shuō)明為負(fù)值,取反方向,數(shù)組長(zhǎng)度加本身,反作用取索引
        return value >= 0 ? value : _handler(value)
    }

    function handlerCount(value) {
        // 如果個(gè)數(shù)比長(zhǎng)度還大,將總長(zhǎng)度賦值給個(gè)數(shù)
        return Math.min(Math.floor(value), _this.length)
    }
    return function(index, count, ...addArr) {
        _this = this
        index = Number(handlerType(index) ? handlerIndex(index) : 0) //準(zhǔn)備刪除的位置
        count = Number(handlerType(count) ? handlerCount(count) : 0) //刪除的個(gè)數(shù)
        count = Math.min(this.length - index, count) //如果刪除的個(gè)數(shù)大于該索引之后的總長(zhǎng)度,取之后的總長(zhǎng)度
        count = Math.max(count, 0)

        let delIndexArr = [] //刪除數(shù)組的索引
        let result = [] //返回的數(shù)組
        for (let i = index; i < index + count; i++) {
            delIndexArr.push(i)
        }
        let finishArr = [] //存放處理之后的數(shù)組
            // 把索引之前的原數(shù)組成員全放到新數(shù)組里去
        this.forEach((im, idx) => {
                if (idx < index) {
                    finishArr.push(im)
                }
            })
            // 處理返回值
        delIndexArr.forEach((im) => {
                result.push(this[im])
            })
            // 把用戶(hù)輸入需要添加的元素放到新數(shù)組里去
        for (let i = 0; i < addArr.length; i++) {
            finishArr.push(addArr[i])
        }
        // 把添加之后,原數(shù)組的剩余成員,全部添加到新數(shù)組
        for (let i = index + count; i < this.length; i++) {
            finishArr.push(this[i])
        }
        // 將新數(shù)組深拷貝給原數(shù)組
        this.length = finishArr.length
        for (let i = 0; i < this.length; i++) {
            this[i] = finishArr[i]
        }
        return result
    }
})()
let arr = ['first', 'second', 'third']
let arr2 = [1, 2, 3, 4, 5];
console.log(arr2.splice(-20, 1, 10)) //1
console.log(arr2) //[10,2,3,4,5]
console.log(arr.mySplice(2, 1)) //[third]
console.log(arr) //[first,second]

?

本文摘自 :https://blog.51cto.com/u

開(kāi)通會(huì)員,享受整站包年服務(wù)立即開(kāi)通 >