JS Array 方法 以及 实现 过程 汇总

熟悉了JS一些方法,你才能运营JS得心应手,这里给出一些常用方法以及实现过程

//splice
Array.prototype.splice =function(start,delLen,item){
	var len =this.length;
	start = start<0?0:start>len?len:start?start:0;
	delLen=delLen<0?0:delLen>len?len:delLen?delLen:len;	
	
	var arr =[],res=[];
	var iarr=0,ires=0,i=0;
	
	for(i=0;i<len;i++){
		if(i<start|| ires>=delLen)	arr[iarr++]=this[i];
		else {
			res[ires++]=this[i];
			if(item&&ires==delLen){
				arr[iarr++]=item;
			}
		}	
	}
	if(item&&ires<delLen) arr[iarr]=item; 
	
	for(var i=0;i<arr.length;i++){
		this[i]=arr[i];
	}
	this.length=arr.length;
	return res;
};


Array.prototype.shift =function(){ if(!this) return[];return this.splice(0,1)[0];}

//分开添加,关键字shallow copy,如果遇到数组,复制数组中的元素
Array.prototype.concat = function(){
	var i=0;
	while(i<arguments.length){
		if(typeof arguments[i] === 'object'&&typeof arguments[i].splice ==='function' &&!arguments[i].propertyIsEnumerable('length')){
		// NOT SHALLOW COPY BELOW
		//	Array.prototype.concat.apply(this,arguments[i++]);
			var j=0;
			while(j<arguments[i].length)	this.splice(this.length,0,arguments[i][j++]);
			i++;
		} else{
			this[this.length]=arguments[i++];
		}
	}
	return this;
}

Array.prototype.join=function(separator){
	var i=0,str="";
	while(i<this.length) str+=this[i++]+separator;
	return str;
}

Array.prototype.pop = function() { return this.splice(this.length-1,1)[0];}

Array.prototype.push = function(){ 
	Array.prototype.splice.apply(this,
		[this.length,0].concat(Array.prototype.slice.apply(arguments))); //这里没有直接处理参数,而是复制了一下
	return this.length;
}



Array.prototype.reverse = function(){
	for(var i=0;i<this.length/2;i++){
		var temp = this[i];
		this[i]= this[this.length-1-i];
		this[this.length-1-i] = temp;
	}
	return this;
}



Array.prototype.slice =function(start,end){
	
	var len =this.length;
	start=start<0?start+=len:start?start:0;
	end =end<0?end+=len:end>len?len:end?end:len;
			
	var i=start;
	var res = [];
	while(i<end){
		res.push(this[i++]);
	}
	return res;	
}
// sort is the  most horrible function
Array.prototype.sort=function(fn){
	if (!(fn && typeof fn ==='function')) fn=function(a,b)  {	return a.toString()<b.toString()?-1:a.toString()>b.toString()?1:0;}
	for(var i=0;i<this.length-1;i++)
		for(var j=i;j<this.length;j++)
			if(fn(this[i],this[j])==1){
				var temp =this[i];
				this[i]=this[j];
				this[j]=temp;				
			}	
	return this;
}

//arr.unshift(ele1,ele2,ele3....)
Array.prototype.unshift =function(){
		Array.prototype.splice.apply(this,[0,0].concat(Array.prototype.slice.apply(this,arguments)));
}










评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值