小编mut*_*nka的帖子

为什么这个类似数组的对象表现得像这样?

通过将对象的原型方法设置为Array方法,该对象的行为类似于对象和数组之间的混合.下面是一个简单的例子:

function Foo() {}
Foo.prototype.push = Array.prototype.push;
Foo.prototype.forEach = Array.prototype.forEach;

var foo = new Foo();

foo.push('abc');

foo.length; // = 1 as expected. But wait, why isn't foo.length undefined? How/when did this property get attached to foo? 

foo[1] = 'def';

foo.length; // still = 1. But foo={0:'abc',1:'def'}, Why not =2?

foo.forEach(function(item) {
  console.log(item)
}); //shows only'abc' and not 'def'

foo.push('ghi');

foo.length; // = 2, and now foo = {0:'abc', 1:'ghi'}. So it overwrote the key=1, which means its accessing the same …
Run Code Online (Sandbox Code Playgroud)

javascript arrays prototype object ecmascript-6

2
推荐指数
1
解决办法
407
查看次数

标签 统计

arrays ×1

ecmascript-6 ×1

javascript ×1

object ×1

prototype ×1