1.重构方法之 push()方法
var arr = [1, 322, 44, 'wo'];
Array.prototype.myPush = function () {
for (var i = 0; i < arguments.length; i++) {
this[this.length] = arguments[i];
}
return this.length;
}
console.log(arr.myPush(2, 233)); // 6
console.log(arr); //[ 1, 322, 44, 'wo', 2, 233 ]
2.重构方法之 pop()方法
var arr = [1, 322, 44, 'wo'];
Array.prototype.myPop = function () {
if (this.length == 0) {
return undefined;
}
var lastElement = this[this.length - 1];
this.length = this.length - 1;
return lastElement;
}
console.log(arr.myPop()); // wo
console.log(arr); // [ 1, 322, 44 ]
3.重构方法之 shift()方法
var arr = [1, 322, 44, 'wo'];
Array.prototype.myShift = function () {
if (this.length == 0) {
return undefined;
}
var firstElement = this[0];
for (var i = 0; i < this.length - 1; i++) {
this[i] = this[i + 1];
}
this.length = this.length - 1;
return firstElement;
}
console.log(arr.myShift()); // 1
console.log(arr); // [ 322, 44, 'wo' ]
4.重构方法之 unshift()方法
var arr = [1, 322, 44, 'wo'];
Array.prototype.myUnshift = function () {
var len = this.length + arguments.length;
for (var i = len - 1; i >= 0; i--) {
//原数组当前的下标 > 参数数组长度-1 就进行数组的前进
if (i > arguments.length - 1) {
this[i] = this[i - arguments.length];
} else { //把参数数组插入到原数组
this[i] = arguments[i];
}
}
return this.length;
}
console.log(arr.myUnshift(22, "aa")); //6
console.log(arr); // [ 22, 'aa', 1, 322, 44, 'wo' ]
5.重构方法之 forEach()方法
var arr = [1, 322, 44, 'wo'];
Array.prototype.myForEach = function (fun) {
for (var i = 0; i < this.length; i++) {
fun(this[i], i, this);
}
}
arr.myForEach((item, index, arr) => {
console.log(item, index, arr);
})
//运行结果:
// 1 0 [ 1, 322, 44, 'wo' ]
// 322 1 [ 1, 322, 44, 'wo' ]
// 44 2 [ 1, 322, 44, 'wo' ]
// wo 3 [ 1, 322, 44, 'wo' ]