Daily-Interview-Question icon indicating copy to clipboard operation
Daily-Interview-Question copied to clipboard

类数组处理

Open wjc7jx opened this issue 7 months ago • 0 comments

我使用Chrome打印为

{
    "2": 1,
    "3": 2,
    "length": 4
}

分析:

  1. push 方法的行为: Array.prototype.push 方法根据对象的 length 属性决定插入位置。调用 push 时,元素会被添加到索引 length 处,并将 length 加 1。
  2. 第一次 push(1): 初始 length 为 2,元素 1 被添加到索引 2,覆盖原值 3。 length 变为 3。
  3. 第二次 push(2): 当前 length 为 3,元素 2 被添加到索引 3,覆盖原值 4。 length 变为 4。
  4. 类数组的显示优化: 对象包含 splice 方法和 length 属性,控制台(如 Chrome)会将其视为类数组,优先显示索引属性,隐藏非数字键(如 push 和 splice 方法)。

wjc7jx avatar Mar 12 '25 00:03 wjc7jx