1、mySlice()
//mySplice 選取數組的的一部分,並返回一個新數組
Array.prototype.mySlice = function(start,end){
var arr = [];
if(arguments.length == 0){ //若是不傳參數,返回一個原數組副本
start = 0;
end = this.length;
}else{ //加工傳進來start參數,使他符合循環要求
start = Number(start);
if(Number.isNaN(start)){
start = 0;
}else if(start < 0){
if(start < -(this.length)){
start = -this.length;
}
start = start + this.length;
}
}
if(arguments.length == 2){ //加工傳進來end參數,使他符合循環要求
end = Number(end);
if(Number.isNaN(end)){
end = this.length;
}else if(end < 0){
if(end < -(this.length)){
end = -this.length;
}
end = end + this.length;
}else if(end > this.length){
end = this.length;
}
}
if(end == undefined){ //若是沒傳end參數,默認設爲數組長度
end = this.length;
}
for(var i = Math.floor(start); i < Math.floor(end) ; i++){
arr.myPush(this[i]);
}
return arr;
}
2、mySplice()
//mySplice 從數組中添加或刪除元素
Array.prototype.mySplice = function(){
var index,howmany;
if(arguments.length == 0){
this.length = 0;
return this;
}else if(arguments.length == 1){ //調整index和howmany的值
index = arguments[0];
if(index >= this.length){
index = this.length;
}else if(index < -this.length){
index = 0;
}else if(index < 0 && index >= -(this.length)){
index += this.length;
}
howmany = this.length - index;
}else if(arguments.length >= 2){ //調整index和howmany的值
index = arguments[0];
if(index >= this.length){
index = this.length;
}else if(index < -this.length){
index = 0;
}else if(index < 0 && index >= -(this.length)){
index += this.length;
}
howmany = arguments[1];
if(index+howmany >= this.length){
howmany = this.length - index;
}
}
var t1 = index;
var length = arguments.length - 2;
var arr = [];
for(var i = 0 ; i < howmany ; i++){ // 返回刪除的數組
arr[i] = this[t1++];
}
var t2 = index;
for(var i = t2 + howmany ; i < this.length ; i++){ //刪除操做後的數組
this[t2++] = this[i];
}
this.length = this.length - howmany;
if(arguments.length > 2){ //插入數
var lastLength = this.length;
var leap = lastLength - index;
var arIndexRigtht = arguments.length - 1;
this.length = this.length + arguments.length - 2;
for(var j = this.length - 1 ; j >= index ; j--){
if(leap > 0){
this[j] = this[j - arguments.length + 2];
leap = leap -1 ;
}else{
this[j] = arguments[arIndexRigtht--];
}
}
}
return arr;
}
好吧,這兩個方法感受都寫的很臃腫,往後能力提高了再修改吧。固然若是能提好的建議那就再好不過了。 ^_^