数组中的slice

作者: 晚月川 | 来源:发表于2020-03-27 22:46 被阅读0次

slice 实现数组的查询

slice(n,m):从数组索引n开始,查找到索引为m处(不含m),把查找到的内容以新数组的形式返回(m不写直接查找到数组末尾)
n不写,m为0,可以理解为把原始数组中的每一项都查找到,以新数组返回,实现出“数组的克隆”,得到的新数组和原始数组是两个不同的数组(两个不同的堆),但是堆中存储的内容是一样的
n如果为负数,那么它从数组尾部算开始位置,也就是-1是指最后一个元素,-2指倒数第二个元素;m为负数时,也是从数组尾部开始算起 (简单地说:如果n/m为负数时,使用length+n/m(此处的length是数组的长度))
如果m<=n,不会复制任何元素到新数组,会返回一个空数组

======================================================

重写数组中内置slice方法

 Array.prototype._slice = function (n, m) {
            // 创建一个变量接收返回值
            var obj = [];
            // 创建一个变量接收当前数组长度
            var leng = this.length;
            // 判断n和m是否为非有效数字,非有效数字默认值为0,有效数字则不做改变
            n = Number((isNaN(n) ? 0 : n));
            m = Number((isNaN(m) ? 0 : m));
            // n和m的取值范围
            // n为正数(或者0)情况下保持不变;否则采用leng+n(leng为当前数组长度)
            n = (n >= 0) ? Math.ceil(n) : Math.ceil(leng + n);
            // m为正数情况下,给m一个取值范围,不能让m超出当前数组索引范围;否则采用leng+m的方式(leng为当前数组长度)
            m = (m >= 0) ? Math.ceil(Math.min(m, leng)) : Math.ceil(leng + m);
            // 创建一个变量用来接收截取范围的长度
            var item = m - n;
            // 截取范围为正数时正常截取,为负数时无法截取,直接返回一个空数组
            if (item > 0) {
                // 当截取范围为正数时,给数组创建一个实例,用来存储当前截取到的数组
                obj = new Array(item);
                for (var i = 0; i < item; i++) {
                    // 遍历数组中的每一项,把截取到的值都存到新数组obj中
                    obj[i] = this[i + n];
                }
            } else {
                // 当截取到的数组长度为零时,返回一个空数组
                return obj;
            }
            // 循环结束、条件结束,返回截取到的数组给外面使用
            return obj;
        };
        let re = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
        console.log(re._slice(1,5));
        // console.log(re.slice(1, 5));
        console.log(re._slice(-1,-5));
        console.log(re._slice(-5,-1));
        console.log(re._slice(11,5));
        console.log(re._slice(0.5,5.7));
        console.log(re._slice('undefined',5));
        console.log(re._slice(6,'呵呵'));
        console.log(re._slice(1,5,7));
        console.log(re._slice(-1.6,-5.7));
        console.log(re._slice(-5.7,-1.6));
        console.log(re._slice(99));
        console.log(re._slice(0,99));
        console.log(re._slice(false));
        console.log(re._slice(NaN));
        console.log(re._slice(NaN,57));
        console.log(re._slice(''));
        console.log(re._slice(true));
        console.log(re._slice('呵呵'));

相关文章

网友评论

    本文标题:数组中的slice

    本文链接:https://www.haomeiwen.com/subject/hlhduhtx.html