0

i confuse about array

my data is

enter image description here

and my for loop

 for (var data in statInfo["segment"][0]) {
       console.log(data)
 }

and my result is

data print is

segment5 segment4 segment3 segment2 segment1

thank you

P.N.
  • 645
  • 6
  • 18
Zeing
  • 15
  • 1
  • 8
  • 4
    Object properties do not have an order. If you need it in order, use an array. – str Dec 14 '16 at 09:35
  • 1
    You're looping over an object and not an array. – Matt Dec 14 '16 at 09:36
  • 1
    And if it was an array (which is not), [using “for…in” with array iteration is a bad idea](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea#500531). – Álvaro González Dec 14 '16 at 09:38
  • Possible duplicate of [Does JavaScript Guarantee Object Property Order?](http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – Álvaro González Dec 14 '16 at 09:39

1 Answers1

2

Enumeration of object properties is not alphabetical.

In fact it is left to implementations to decide.

Most browsers implement according to order of property creation IIRC.

If you need ordering use an Array, Map or Set.

Finally, in ES2015, you can make an object iterable by defining your own iteration function, which can have any order or enumeration you need.

var obj = { 
    foo: '1', 
    bar: '2',
    bam: '3',
    bat: '4',
};

obj[Symbol.iterator] = iter.bind(null, obj);

function* iter(o) {
    var keys = Object.keys(o);
    for (var i=0; i<keys.length; i++) {
        yield o[keys[i]];
    }
}

for(var v of obj) { console.log(v); } // '1', '2', '3', '4'
Community
  • 1
  • 1
Ben Aston
  • 53,718
  • 65
  • 205
  • 331