【问题标题】:Reusing built-in array methods - JS - Confused重用内置数组方法 - JS - 困惑
【发布时间】: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


【解决方案1】:

因为本机.push 方法explicitly 采用它所调用的类数组对象的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).

所有这些值都存储在哪里?

在对象的length 属性上。它不是隐藏的内部插槽。

【讨论】:

  • “关于对象的长度属性” - 我认为 OP 的意思是询问传递给gather 函数的值在哪里,即'first''second'被存储了吗?
猜你喜欢
  • 2017-10-08
  • 1970-01-01
  • 2014-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多