In learning JavaScript for… When looping in, you are always told to loop through objects in an unreliable order of attributes, so do not loop in for… In makes logical judgments that depend on the order of object attributes.

But when we write an object ourselves, we refresh it several times and find that the properties loop out in the same order.

let user = {
  name: "John".age: 30.isAdmin: true
};

for(let key in user) {
  console.log( key ); // Name age isAdmin ← is the same
}

// Do not write an object
let tom = {
  gender: 'male'.hasGirlfriend: false.isFunny: true
};

for(let key in tom) {
  console.log( key ); // Gender hasGirlfriend isFunny ← Is the same
}
Copy the code

What’s going on? I read a passage today that explains why… What is the order of object properties in the in loop?

After reading it, I understand. Now I want to share it with you.

It boils down to this: The integer properties are iterated through first, in ascending order, and then the other properties are iterated through in the order they were created.

Let’s look at an example:

let codes = {
  "49": "Germany"."41": "Switzerland"."44": "Great Britain"."1": "USA"
};

for(let code in codes) {
  alert(code); // 1, 41, 44, 49
}
Copy the code

The result of the final traversal is: attribute 1 is traversed first, and attribute 49 is traversed last.

Here 1, 41, 44, and 49 are integer attributes.

So what is an integer property? We can use the following comparison results to illustrate:

String(Math.trunc(Number(prop)) === prop
Copy the code

Prop is an integer property if true, otherwise it is not.

so

  • "49"Is an integer property becauseString(Math.trunc(Number('49'))The result is still"49".
  • "+ 49"It’s not an integer property becauseString(Math.trunc(Number('+49'))As a result of the"49", not"+ 49".
  • "1.2"It’s not an integer property becauseString (Math. Trunc (Number (' 1.2 '))As a result of the"1", not"1.2".

In the above example, if you wanted to loop through the creation order, you could use a neat method:

let codes = {
  "+ 49": "Germany"."+ 41": "Switzerland"."+ 44": "Great Britain"./ /.. .
  "+ 1": "USA"
};

for(let code in codes) {
  console.log( +code ); // 49, 41, 44, 1
}
Copy the code

(after)