1 以下代码的输出结果
js
let obj = {
2: 3,
3: 4,
length: 2,
push: Array.prototype.push
}
/**
* Array.prototype.push = function () {
this[this.length] = val;
this.length++;
}
obj.push(1)执行过程中
obj[obj.length]=1 =>obj[2]=1
obj.length++ =>obj.length=3
obj.push(2)执行过程中
obj[obj.length]=2 =>obj[3]=2
obj.length++ =>obj.length=4
*/
obj.push(1);
obj.push(2);
console.log(obj);
//所以最终输出
// {
// 2: 1,
// 3: 2,
// length: 4,
// push: Array.prototype.push
// }2 类数组想用数组的方法的解决方案总结
js
let obj={
0:10,
1:20,
length:2
}解决方案1:改变
this
js
[].forEach.call(obj,item=>{
console.log(item);// 10,20
})- 解决方案2:改变原型指向
js
obj.__proto__=Array.prototype- 解决方案3:把需要用的方法作为
obj的一个私有属性
js
obj.each=Array.prototype.forEach;