Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

obj = {
 1: 'a',
 2: 'b',
 length: 2,
 push: Array.prototype.push
 }

 obj.push('c')

 console.log(obj.length) //3
 console.log(obj[0]) // undefined
 console.log(obj[1]) // a
 console.log(obj[2]) // c
 console.log(obj[3]) // undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.7k views
Welcome To Ask or Share your Answers For Others

1 Answer

obj的push方法借用了Array的push,push的时候会根据实例(一般是数组,这里因为内部this实际指向obj即修改的是obj)的length添加索引属性,如该示例length为2,则添加属性2:'c'[覆盖了原有的2:'b'],并且修改实例length+1,最终结果如输出所示


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...