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

本文探讨了当一个对象的属性值为Array.prototype.push时,如何调用该属性并理解其工作原理。通过示例展示了Array.prototype.push方法如何在对象上添加元素,并分析了其实现方式。此外,还提供了自定义实现myPush的方法,帮助读者更清晰地理解数组尾部添加元素的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值