【发布时间】:2021-09-26 19:39:32
【问题描述】:
这是一段我无法推理的代码。 这些原型数组方法用于 elems 对象,但我不明白为什么 length 会受到它的影响。没有任何已定义的数组。然而,每个添加操作(通过收集方法)都会增加“长度”。这个对象如何表现得像一个数组?所有这些值都存储在哪里?有人可以解释一下吗?
const elems = {
length: 0,
add: function(elem) {
Array.prototype.push.call(this, elem);
},
gather: function(id) {
this.add(document.getElementById(id))
},
find: function(callback) {
return Array.prototype.find.call(this, callback);
},
}
elems.gather('first');
console.log(elems.length === 1);
elems.gather('second');
console.log(elems.length === 2);
const found = elems.find((elem) => elem.id === 'second');
console.log(found.id === 'second');
<h1 id='first'>Hello</h1>
<h1 id='second'>Stack!</h1>
【问题讨论】:
-
length属性已更改,因为this已传递给.call()方法。 -
“所有这些值都存储在哪里?” - 它们存储在
elem对象中,其中key 是索引,value 是html 字符串;尝试记录elem对象。
标签: javascript arrays object prototype