簡體   English   中英

重用內置數組方法 - JS - 困惑

[英]Reusing built-in array methods - JS - Confused

這是一段我無法推理的代碼。 這些原型數組方法用於elems對象,但我不明白為什么長度會受到它的影響。 沒有任何已定義的數組。 然而,每個添加操作(通過gather 方法)都會增加“長度”。 這個對象如何表現得像一個數組? 所有這些值都存儲在哪里? 有人可以對此有所了解嗎?

 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方法顯式獲取調用它的類數組對象的長度,將其加一,並將該結果分配給新的.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).

所有這些值都存儲在哪里?

關於對象的length屬性。 它不是隱藏的內部插槽。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM