Insert and remove random JavaScript array indices

I insert some elements into an array with randomly generated indexes, for example:

var myArray = new Array();
myArray[123] = "foo";
myArray[456] = "bar";
myArray[789] = "baz";
...

In other words, array indices do not start from zero, and there will be "numeric spaces" between them. My questions:

  • Will these numeric spaces be allocated in some way (and therefore take some memory) even if they have no assigned values?
  • When I remove myArray [456] from the top example, will the elements be moved below this element?

EDIT: Regarding my question / concern about wrapping items after insertion / deletion - I want to know what happens to memory, not indexes. Additional information from the wikipedia article :

Linked lists have several advantages over dynamic arrays. Inserting an element at a certain point in the list is a constant-time operation, whereas inserting randomly into places in a dynamic array will require you to move half the elements on average, and all elements in the worst case. Although one can "remove" an element from the array at a constant time, somehow marking its slot as "free", this causes fragmentation, which hinders the iteration performance.

+3
source share
3 answers

Will these numeric spaces be allocated in some way (and therefore take some memory) even if they have no assigned values?

. JavaScript (. ), .

myArray [456] , ?

, , : delete, . splice , . , () , , (- delete splice pop ) . JavaScript , . JavaScript ( ) (, , , , B- , ), .

, , , . , length , . :

var obj = {};
obj[123] = "foo";
obj[456] = "bar";
obj[789] = "baz";

JavaScript. , (123 ..), ( , ), "123" .. ( , Array Object). for..in ( ).


"... "? . JavaScript key- > value, JavaScript - , , , , , length. "" , , — a[0] a["0"] ( , ). 15.4 , :

. P ( String) , ToString (ToUint32 (P)) P ToUint32 (P) 2 ^ 32-1. , , . Array length, 2 ^ 32. length , ; Array , . , , , , length , , , ; , length , , , , . Array , .

+6

- (, , ), ?

, . .

myArray [456] , ?

, 460 , 456. , , splice:

myArray.splice(456, 1)
+1

“Gaps” will not lead to distribution, and no, there is no “bias” of existing values ​​from their indices.

+1
source

Source: https://habr.com/ru/post/1782851/


All Articles