Adakah Tatasusunan JavaScript Benar-Benar Padat, atau Adakah Ia Menunjukkan Gelagat Jarang?

Barbara Streisand
Lepaskan: 2024-11-13 10:32:02
asal
806 orang telah melayarinya

Are JavaScript Arrays Truly Dense, or Do They Exhibit Sparse Behavior?

Sparse Nature of Javascript Arrays

In Javascript, arrays are inherently sparse, meaning that they do not automatically allocate memory for all elements between 0 and the current index. Instead, elements are only allocated when they are accessed or assigned.

For instance, consider the following code, where we set an element at the current time as the index:

array[Date.getTime()] = value;
Salin selepas log masuk

Contrary to what you might expect, this does not cause the interpreter to allocate all elements from 0 to the current moment. Instead, it only allocates the specific element that is accessed.

Hash Table Implementation

Javascript arrays are internally implemented as hash tables. This means that keys (indices) can not only be integers but also strings, floats, or objects. Upon insertion into the hash table, all keys are converted to strings using the toString() method.

Verification Code

You can verify this sparse nature with the following test code:

var array = [];
array[0] = "zero";
array[new Date().getTime()] = "now";
array[3.14] = "pi";

for (var i in array) {
  console.log("array[" + i + "] = " + array[i] + ", typeof(" + i + ") == " + typeof(i));
}
Salin selepas log masuk

This code iterates over the actual defined indices and outputs:

array[0] = zero, typeof(0) == string
array[1254503972355] = now, typeof(1254503972355) == string
array[3.14] = pi, typeof(3.14) == string
Salin selepas log masuk

which demonstrates that non-integer indices also work without allocating intermediate elements. However, note that using the traditional for loop with i ranging from 0 to array.length can lead to issues with non-standard array indices.

Atas ialah kandungan terperinci Adakah Tatasusunan JavaScript Benar-Benar Padat, atau Adakah Ia Menunjukkan Gelagat Jarang?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan