类数组要求:
- 属性为索引(数字)属性
- 必须有lenght属性
- 最好有push 属性
push方法实现原理
Array.prototype.push = function (target){
this.[this.length] = target
this.length++
}
试题
var obj = {
"2" : "a",
"3" : "b",
"length" : 2,
"push" : Array.prototype.push
}
// 往类数组里面添加"c","d",打印出结果
obj.push('C')
obj.push('D')
console.log(obj) //{2: "C", 3: "D", length: 4, push: ƒ}
// 需要理解push的原理
// this.length=2,obj["2"],也就是目前的"a"对应的属性,传入的target会将原本的"a"覆盖掉
// 同理 "d"也是这样添加进去
// length最终值为4 ,在2的基础上累加的缘故