slice方法重写及常见应用

数组的原型上有一个方法叫做slice,给不同的参数组合会返回不同的结果,由于组合非常多,这里研究一下不同组合的结果并基于原型链对该方法进行仿写
考虑情况:

slice(a,b) slice(a) slice(undefined,b) slice()
a<b,a>=b,a为负数(0),b为负数(0),b超出有效长度了,a,b非有效数字

源码如下: 不想看源码的请直接看最下面的结果…

Array.prototype.mySlice = function (a, b) {
        var newArr = [];
        //处理没有参数的情况
        if (a === undefined && b === undefined) {
            return this
        }
        //处理只有一个参数,或者是第二个参数大于数组长度的情况
        if (b === undefined || b > this.length) {
            b = this.length
        }
        if (a === undefined) {
            a = 0
        }
        //处理参数不是数字的情况(上面代码已经将undefined参数转化为非undefined参数并且保证参数为两个了)
        if (typeof a !== 'number'  || typeof b !== 'number' ) {
            console.log('参数必须是数字')
        }
        //处理第一个参数为负数以及第一个参数大与第二个参数以及第二个参数是负数的情况的情况

        if (b < 0) {
            b = this.length + b
        }
        if (a < 0) {
            a = this.length + a
        }
        //先将a,b恢复成正数再比较
        if (a >= b || b === 0) {
            return []
        }
        //正常 slice(a,b)
        for (var i = a; i < b; i++) {
            newArr.push(this[i])
        }
        return newArr
    }

考虑到验证正确性,增加一个验证函数

function check(testArr, n, m) {
        console.log(`[${testArr}].slice(${n},${m})--->[${testArr.slice(n, m)}]`, testArr.slice(n, m).toString() === testArr.mySlice(n, m).toString());
    }
     
    check([1, 2, 3, 4, 5], 1, 3);
    check([1, 2, 3, 4, 5], 1);
    check([1, 2, 3, 4, 5], undefined, 3);
    check([1, 2, 3, 4, 5], 1, 7);
    check([1, 2, 3, 4, 5]);
    check([1, 2, 3, 4, 5], -1, 3);
    check([1, 2, 3, 4, 5], -3, 3);
    check([1, 2, 3, 4, 5], 1, 0);
    check([1, 2, 3, 4, 5], 1, -1);
    check([1, 2, 3, 4, 5], 1, -2);
    check([1, 2, 3, 4, 5], 1, -3);
    check([1, 2, 3, 4, 5], 3, 1);

结果如下:
《slice方法重写及常见应用》

比较常见的应用:

  1. 数组的复制

       arr.slice()
  2. 类数组转化为数组(dom类数组不兼容IE6,7,可以用ES6中arr.from()替换)

    Array.prototype.slice(类数组)
    
  3. 子数组的获取
    3.1 正常的自数组获取

       arr.slice(m,n) (0<m<n<arr.length)

    3.2 模拟多次pop() shift()

       比如n次pop   arr = arr.slice(undefined,-n)
       比如n次shift   arr = arr.slice(n)
    
    原文作者:Runningfyy
    原文地址: https://segmentfault.com/a/1190000015805382
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞