一个对象属性值为Array.prototype.push,当我们调用这个对象的对应属性时

一个对象属性值为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);

如何解决这个问题

  1. 我们需要知道Array.prototype.push这个方法到底发生了什么,
  2. Array.prototype.push(55),传入的是一个数字
  3. 返回值是一个数组最新的length,数组的长度
  4. Array.prototype.push()是往数组的最末尾添加元素
  5. 那么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));//4
arr.myPush(88) ---> arr[this.length] ----> arr[3] = 88
        console.log(arr); 
        {
    
    
        
        };
        //Array.prototype.push大致是这样实现的
        
        

解题

let obj = {
    
    
   1:12,
   2:89,
   3:'李华',
   push:Array.prototype.push,
   length:4
   
};
console.log(obj.push(1)); // 5
console.log(obj.push(2));// 6
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

}



猜你喜欢

转载自blog.csdn.net/webMinStudent/article/details/109118447