前言:
数组API的调用使得我们在js的使用中更加方便和快捷,而今天我们要探索数组API方法的底层原理,接下来和大家一起学习数组中的一些方法重构。
我们主要学习一下,栈与队列方法、迭代方法两种数组API重构。
一、栈与队列方法
- myPush()
- myPop()
- myUnshift()
- myshift()
1.myPush()
重写push方法()
可接受任意类型的参数,将它们逐个添加到数组的末尾,并返回数组的长度.
//1.在原型中添加自写的push
Array.prototype.myPush = function () {
//2.使用arguments接收传进来的参数,遍历传进来了多少个
for (var i = 0; i <= arguments.length-1; i++) {
//3.将遍历的arguments中的值添加进数组里
this[this.length] = arguments[i];
}
// 4.返回数组的长度
return this.length;
}
var arr = new Array();
arr = [1, 2, 3, 4, 5];
//例子1:
console.log(arr.myPush(6, 7, 8, 9));//9
console.log(arr);
//[
// 1, 2, 3, 4, 5,
// 6, 7, 8, 9
// ]
//例子2:
//console.log(arr.myPush({}));//6
// console.log(arr);//[ 1, 2, 3, 4, 5, {} ]
2.myPop()
重写pop()方法
从数组的末尾移除最后一项,减少数组的length值,返回移除的项
Array.prototype.myPop = function () {
if (this.length == 0) {
// 判断数组是否为空
return undefined;
}
//先返回最后一个值
var last = this[this.length - 1];
//移除最后一个值
this.length = this.length - 1;
return last;
}
var arr = new Array();
//例子1:
arr = [1, 2, 3, 4, 5];
console.log(arr.myPop()); //5
console.log(arr); //[ 1, 2, 3, 4 ]
//例子2:
// arr = [];
// console.log(arr.myPop());//undefined
3.myUnshift()
myUnshift()
方法可向数组的开头添加一个或更多元素,并返回新的长度。
Array.prototype.myUnshift = function () {
for (var i = this.length + arguments.length - 1; i >= 0; i--) {
/