I am trying to understand what's the thing with javascript Objects while using them as an associative array.
From ECMA:
4.3.3 An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.
Using them in browser (chrome):
x = { 2: 'a', 3: 'b', 1: 'c' }
> Object {1: "c", 2: "a", 3: "b"}
y = { 'b': 2, 'c': 3, 'a': 1 }
> Object {b: 2, c: 3, a: 1}
While in the first example with the numbers as keys, they became ordered, in the second example with strings, they won't ( ordered = a,b,c ).
I am using these objects with string keys and I really don't want them to change order in some stage of app(if that's even possible) because it may crash the pipeline I am using.
Question is, is this approach safe and normal for every javascript machine, or should I use other method to guarantee that order won't ever change?
Thank you!
Edit: I am using this with node.js which runs on V8 (chrome engine), which 'orders non-numerical properties in insertion order'(Felix Kling). May this behaviour of V8 change?
Although Chrome may guarantee property order when using numbers as indexes in objects, the ECMA specification does not say it should do that, so by guarantee I'd not rely on this behavior. I suggest you to restructure your data to use arrays when you want to keep data order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With