数组的push方法
数组的push方法相信大家都非常熟悉了,但是push方法的实现原理,又是怎么样的呢,首先来看一道题:
let obj = {
2: 'a',
3: 'b',
length: 2,
push: Array.prototype.push
}
obj.push('c', 'd');
console.log(obj)
现在打印出来的obj是什么?
答案:
obj = {2:'c', 3: 'd', length: 4, push: Array.prototype.push}
为什么会这样呢,来看一下push的实现原理就知道了
Array.prototype.myPush = function(...args) {
for(let i = 0; i < args.length; i++) {
this[this.length++] = args[i];
}
return this.length;
}
let obj1 = {
2: 'a',
3: 'b',
length: 2,
push: Array.prototype.myPush
}
obj1.push('c', 'd');
console.log(obj1) //{2:'c', 3: 'd', length: 4, push: Array.prototype.myPush}
结果相同

浙公网安备 33010602011771号