为什么`[1, 2, 3]`在控制台中没有显示为`Array(3)`?

问题描述 投票:0回答:1

当我检查数组的实例(如

const arr = [1, 2, 3];
)时,该数组的原型链将指向
Array.prototype


但是,我不明白为什么

Array.prototype
Array(0)
中显示为空数组(
Chrome console.log()
)?


enter image description here

我已经阅读了post1post2,但仍然无法理解这个基本概念。


为什么控制台中的

[1, 2, 3]
没有显示为
Array(3)


javascript node.js arrays google-chrome
1个回答
0
投票

在 Chrome 的控制台中,Array.prototype 显示为 [](空数组,或 Array(0)),因为它反映了数组的原型对象,而数组本身就是一个没有元素的数组。

这种行为可能会令人困惑,因为 Array.prototype 实际上是一个特殊的对象,具有许多方法,如 push、pop、map、filter 等。当您直接检查它时,Chrome 通过将其显示为空数组 ([]) 来简化输出,以强调它是所有数组的原型,但这并不意味着 Array.prototype 字面上没有属性。

澄清一下:

Array.prototype 是所有数组都继承其方法的对象。 Chrome 将其显示为空数组,因为它是一个内部结构行为类似于数组(没有元素)的对象。 如果您通过在控制台中展开来进一步检查 Array.prototype,您将看到它具有的方法,例如 concat、forEach、map 等。 总之,空数组显示只是一种简写表示,但该对象仍然在底层保留了所有与数组相关的重要方法。

© www.soinside.com 2019 - 2024. All rights reserved.