JavaScript常用字符串与数组扩展函数小结(4)

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))); }

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgyydw.html