briefy / notes

notes to problems encountered
1 stars 0 forks source link

Order in object properties iteration #1

Open briefy opened 7 years ago

briefy commented 7 years ago

This article is based on the following two links, I draw the conclusion https://bugs.chromium.org/p/v8/issues/detail?id=164 http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order

object here only refer to plain object type, not array used as object

the order is not guaranteed by the EMAC spec,however, it is a de-facto way under some circumstance.

  1. you can rely on the order when there is only STRING property OR SYMBOL properties, integer-like ones do not consistent across different vendors of browsers

    if use symbols and no-integer-like strings together, no-integer-like strings will come before symbols(do not recommend to use together)

    some one says that integer-like properties come the very first,however,there is no guarantee across all browser vendors,like FF & safari wont, chrome

    methods can count on Object.getOwnPropertyNames Object.getOwnPropertySymbols Object.keys Reflect.ownKeys for-in loop

    try below

            var a = new Array();
            a["x"] = 2;
            a[Symbol()] = 2;
            a['y'] = 2;
            var s = "";
            for (x in a) { s += x; };
            Reflect.ownKeys(a);
  1. if you want to make sure the order is consistent under all situations ,use ES2015 Map instead
briefy commented 7 years ago

React uses this ,says in the doc as I quote: https://facebook.github.io/react/docs/create-fragment.html

The return value of createFragment should be treated as an opaque object; you can use the React.Children helpers to loop through a fragment but should not access it directly. Note also that we're relying on the JavaScript engine preserving object enumeration order here, which is not guaranteed by the spec but is implemented by all major browsers and VMs for objects with non-numeric keys