Why are javascript numeric keys always sorted before start?

So let's say I have something like the following in javascript:

object = {"one": 1, "two": 2, "three": 3, "123": 123}; 

When I repeat this, it turns out that the "123" element jumped to the top of the list, and the order of the others was maintained. If I do something like the following,

 object = {"one": 1, "two": 2, "three": 3, "123 STRING": 123}; 

order is maintained. Thus, it seems that a purely numeric key is full, but a key containing non-numeric characters is not. Does anyone know why?

+4
source share
4 answers

In V8, the data structures behind the object are very different:

  • Named in-object properties stored directly "on the C-structure"
  • Identification properties outside the object, stored in an array external to the object, additional indirectness
  • Indexed properties (properties whose property names can be converted to integers) are stored in an array external to the object but the array index acts like a key
  • Ordered Hash Table

Named properties are in insertion order, as this is most natural with hidden class evolution / transitions.

Indexed properties are in their actual ordinal value because it would be a waste of memory to store the insertion order.

If you maintain a hash table, the hash table intentionally fakes the same order as the result of natural optimizations.

The same is true in other browsers, since storing indexed properties when numbers are small in a real "C" array is a huge optimization. What can change is whether the indexed properties of the properties of the first or the name are listed.

The spectrum made this optimization possible without defining the iteration order , and V8 was the first (at least according to this stream of errors) to use it.

Indexed keys listed before naming, and vice versa, are of course arbitrary and do not affect optimization.

+2
source

The order of keys in the object is not specified in the ECMAScript standard. In other words, you have no guarantee, the keys can be in any order.

You can check this post: How to save an ordered Javascript object / array while saving key searches?

+2
source

I'm not 100% sure, but this may be due to the fact that there is no implicit order when iterating through the keys, and therefore what you are experiencing seems strange, but this is just a side effect, probably the hash function used for the keys .

The Javascript property package implementation probably uses some kind of tree-like data structure where keys are stored using a hash function.

0
source

Whenever we iterate over an object, we mostly use for in

Iterate in in in in aarbitary

. If order is important, then you should prefer arrays. For different browsers, the order is different.

Refer to the following link: The order of elements in the "for (... in ...)" loop

0
source

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


All Articles