一个对象属性值为Array.prototype.push,当我们调用这个对象对应属性值为Array.prototype.push时
题目
let obj = {
1:12,
2:89,
3:'李华',
push:Array.prototype.push
length:4
};
console.log(obj.push(1));
console.log(obj.push(2));
console.log(obj);
如何解决这个问题
- 我们需要知道Array.prototype.push这个方法到底发生了什么,
- Array.prototype.push(55),传入的是一个数字
- 返回值是一个数组最新的length,数组的长度
- Array.prototype.push()是往数组的最末尾添加元素
- 那么Array.prototype.push()是如何往尾部添加元素的呢?
那么Array.prototype.push()是如何往尾部添加元素的呢?
let arr = {
4:1,
9:8,
3:9,
length:3
}
Object.prototype.myPush = function (value) {
this[this.length] = value
this.length++;
return this.length;
}
console.log(arr.myPush(88));
arr.myPush(88) ---> arr[this.length] ----> arr[3] = 88
console.log(arr);
{
};
解题
let obj = {
1:12,
2:89,
3:'李华',
push:Array.prototype.push,
length:4
};
console.log(obj.push(1));
console.log(obj.push(2));
console.log(obj);
obj.push(1) --------> obj[this.length] ---->obj[4] = 1
{
1:12,
2:89,
3:'李华',
4:1,
push:Array.prototype.push,
length:5
}
obj.push(2) ------->obj[this.length] ------->obj[5] = 2
{
1:12,
2:89,
3:'李华',
4:1,
5:2
pus:Array.prototype.push,
length:6
}