如何在JavaScript中实现“数组”?

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

我宽松地使用该术语,因为JavaScript中的数组看起来像这样:

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

如果我做array.push('end'),我会得到

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

JavaScript中的数组似乎与计算机科学中讲授的适当数组无关,因为所有项目都是同一类型,这使得可以通过索引轻松访问,因为可以使用简单的数学运算来确定每个索引在哪里在内存中。

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

如果有人知道V8引擎的位置,看代码就很酷。

javascript data-structures v8
1个回答
0
投票

可以在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.

因此,当前将数组实现为哈希表或数组列表。过去已经改变了,将来可能会改变。另外,其他引擎可能也会有所不同。

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