要重构一个方法首先得了解:
1、调用方式
2、参数、 是否改变原数组
3、功能
4、返回值
1、push()方法
调用方式:array.push(params)
需要传参数,该方法将改变数组的数目。
push() 方法可向数组的末尾添加一个或多个元素,返回新的数组长度
返回新的数组长度!!!是长度!!Number值
废话不多说上代码!
Array.prototype.mypush = function () {
// arguments类数组
//按索引从小到大循环数组
// arguments,是调用函数时,传入的参数数组
// console.log(arguments);
for (let i = 0; i < arguments.length; i++) {
// 给当前数组的最末端,加入一个新的元素
this[this.length] = arguments[i];
}
return this.length;
}
测试
arr = ["a", "b", "c", "d"];
var len = arr.mypush("e");
console.log(len);// 5