chdyiboke / weekly

issue and share weekly
5 stars 1 forks source link

如果我们遍历一个对象,我们获取属性的顺序是和属性添加时的顺序相同吗 #44

Open liukexina opened 3 years ago

liukexina commented 3 years ago

对于for in循环对象是有一定的顺序的: 简短的回答是:“有特别的顺序”:整数属性会被进行排序,其他属性则按照创建的顺序显示 整数属性:

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

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

其他属性:

let user = {
  name: "John",
  surname: "Smith"
};
user.age = 25; // 增加一个

// 非整数属性是按照创建的顺序来排列的
for (let prop in user) {
  alert( prop ); // name, surname, age
}

如果整数属性和其他属性混合时,整数属性在前其他属性在后

let codes = {
  age: 49,
  "49": "Germany",
  "41": "Switzerland",
  "44": "Great Britain",
  "1": "USA",
  name: 'john'
};

for(let code in codes) {
  console.log(code); // 1, 41, 44, 49, age, name
}