重用内置数组方法 - JS - 困惑
Reusing built-in array methods - JS - Confused
这是一段我无法推理的代码。
这些原型数组方法用于 elems 对象,但我不明白为什么 length 会受到它的影响。没有任何数组被定义。然而,每个添加操作(通过 gather 方法)都会增加 '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>
因为调用它的类数组对象的本机 .push
方法 explicitly takes the length 将其加一,并将该结果分配给新的 .length
属性:
1. Let O be ? ToObject(this value).
2. Let len be ? LengthOfArrayLike(O).
3. Let argCount be the number of elements in items.
4. If len + argCount > 253 - 1, throw a TypeError exception.
5. For each element E of items, do
a. Perform ? Set(O, ! ToString((len)), E, true).
b. Set len to len + 1.
6. Perform ? Set(O, "length", (len), true).
Where are all these values stored in ?
关于对象的length
属性。这不是隐藏的内部插槽。
这是一段我无法推理的代码。 这些原型数组方法用于 elems 对象,但我不明白为什么 length 会受到它的影响。没有任何数组被定义。然而,每个添加操作(通过 gather 方法)都会增加 '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>
因为调用它的类数组对象的本机 .push
方法 explicitly takes the length 将其加一,并将该结果分配给新的 .length
属性:
1. Let O be ? ToObject(this value).
2. Let len be ? LengthOfArrayLike(O).
3. Let argCount be the number of elements in items.
4. If len + argCount > 253 - 1, throw a TypeError exception.
5. For each element E of items, do
a. Perform ? Set(O, ! ToString((len)), E, true).
b. Set len to len + 1.
6. Perform ? Set(O, "length", (len), true).
Where are all these values stored in ?
关于对象的length
属性。这不是隐藏的内部插槽。