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

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

看代码说结果,求解释

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...