使用原型,重寫了數組的push、pop、shift、unshift幾個簡單的方法。
我在這拋磚引玉,期待大神更多對象的其餘的方法擴展數組
Array.prototype.push = function(){ //this: 1,2,3 //arguments: 4,5,6 for (var i = 0; i < arguments.length; i++) { this[this.length] = arguments[i]; } return this.length; } Array.prototype.pop = function(num){ if (num) { this.length = this.length-num }else{ this.length = this.length-1; } return this.length; } Array.prototype.shift = function(){ for (var i = 1; i < this.length; i++) { this[i-1] =this[i]; } this.length = this.length -1; return this.length; } Array.prototype.unshift = function(){ for (var i = this.length-arguments.length-1; i >= 0; i--) { this[arguments.length+i] = this[i]; } for (var j = 0; j < arguments.length; j++) { this[j] =arguments[j]; } return this.length; } var arr = new Array(); arr = [1,2,3]; arr.push(4,5,6); alert(arr); arr.pop(); alert(arr); arr.shift(); alert(arr);//2,3,4,5 arr.unshift("a","b"); alert(arr);//a,b,2,3,4,5