以下是我的一些想法,若有問題感謝您指出來 謝謝
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"]
結果截圖如下:
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/252704.html
標籤:其他

