一、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;
}
二、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;
}
好吧,这两个方法感觉都写的很臃肿,日后能力提升了再修改吧。当然如果能提好的建议那就再好不过了。 ^_^
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。