Array.prototype.replace = function($oldValue, $newValue)
{
for(var $i=0; $i<this.length; $i++)
{
if(this[$i] == $oldValue)
{
this[$i] = $newValue;
return;
}
}
}
Array.prototype.swap = function($a, $b)
{
if($a == $b)
return;
var $tmp = this[$a];
this[$a] = this[$b];
this[$b] = $tmp;
}
Array.prototype.max = function() {
return Math.max.apply({}, this);
}
Array.prototype.min = function() {
return Math.min.apply({}, this);
}
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;
}
//arr.unshift(ele1,ele2,ele3....)
Array.prototype.unshift =function(){
Array.prototype.splice.apply(this,[0,0].concat(Array.prototype.slice.apply(this,arguments)));
}
您可能感兴趣的文章: