实现array.slice()方法

以下是我的一些想法,若有问题感谢您指出来        谢谢

Array.prototype.mySlice = function(...formPara){//不定参数,es6中有介绍
           let length =  formPara.length;
           let temp = [];//要返回的数组
           let start = 0;//默认初始位置为下标0
           let end = this.length;//默认初始位置为下标length-1
           //也就是只有一个参数传进来
           if(length === 1 ){
                start = formPara[0] < 0? end + formPara[0]:formPara[0];
           }
           //传入两个参数
           else if(length === 2){
                start = formPara[0] < 0? end + formPara[0]:formPara[0];
                end = formPara[1] < 0? end + formPara[1]:formPara[1];
                
           }
           for(let i = start;i < end;i++){
                temp.push(this[i]);
           }
           return temp;
        }
let arrary = ['a','b','c','d','e','f'];
    console.log(arrary.mySlice());      //["a", "b", "c", "d", "e", "f"]
    console.log(arrary.mySlice(1));     //["b", "c", "d", "e", "f"]
    console.log(arrary.mySlice(2,3));   //["c"]
    console.log(arrary.mySlice(3,2));   //[]
    console.log(arrary.mySlice(-3,-1)); //["d", "e"]
    console.log(arrary.mySlice(-1,-3)); //[]
    console.log(arrary.mySlice(-3));    //["d", "e", "f"]

 结果截图如下:

实现array.slice()方法_第1张图片

 

 

你可能感兴趣的:(学习回顾)