JS 计算一个对象/Object的长度

1
2
3
4
5
6
7
8
9
10
11
12
13
var bookAuthors = {  
"Farmer Giles of Ham": "J.R.R. Tolkien",
"Out of the Silent Planet": "C.S. Lewis",
"The Place of the Lion": "Charles Williams",
"Poetic Diction": "Owen Barfield"
};
var arr = Object.keys(bookAuthors);

//Outputs: Array [ "Farmer Giles of Ham", "Out of the Silent Planet", "The Place of the Lion", "Poetic Diction" ]
console.log(arr);

//Outputs: 4
console.log(arr.length);

Object.keys() 方法会返回一个由给定对象的所有可枚举自身属性的属性名组成的数组,
数组中属性名的排列顺序和使用for-in循环遍历该对象时返回的顺序一致(两者的主要区别是 for-in 还会遍历出一个对象从其原型链上继承到的可枚举属性)。