"array" 如何在 JavaScript 中实现?

How is an "array" implemented in JavaScript?

我松散地使用这个术语作为数组 JavaScript 可以看起来像这样:

let array = [1, 'a', "hello"];

如果我这样做 array.push('end') 我得到

[1, 'a', "hello", "end"]

JavaScript 中的数组似乎与计算机科学中教授的数组无关,因为所有项目都是同一类型,这使得通过索引访问变得容易,因为可以使用简单的数学运算确定每个索引在内存中的位置。

我的假设是一个单链表,数据是对另一个对象的引用。

如果有人知道 V8 引擎的代码在哪里,那么看到代码会很酷。

可以找到 V8 的源代码 here。目前 V8 以两种方式实现数组:

 // The JSArray describes JavaScript Arrays
 // Such an array can be in one of two modes:
 //    - fast, backing storage is a FixedArray and length <= elements.length();
 //       Please note: push and pop can be used to grow and shrink the array.
 //    - slow, backing storage is a HashTable with numbers as keys.

所以数组目前被实现为哈希表或数组列表。这在过去已经改变,将来可能会改变。其他引擎也可能有所不同。