- 10288
In our daily development, objects are used frequently. It is very convenient for us to calculate the length of arrays, but how to calculate the length of objects?
If we have a library project with a group of books and authors, like the following:
- 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"
- };
We analyze the current requirements. We send data to an API, but the book length cannot exceed 100, so we need to calculate how many books there are in an object before sending data. So what do we always do? We may do this:
- function countProperties (obj) {
- var count = 0;
- for (var property in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, property)) {
- count++;
- }
- }
- return count;
- }
- var bookCount = countProperties(bookAuthors);
- // Outputs: 4
- console.log(bookCount);
- 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);
Let's use the keys method for arrays:
- var arr = ["zuojj", "benjamin", "www.zuojj.com"];
- //Outputs: ["0", "1", "2"]
- console.log(Object.keys(arr));
- //Outputs: 3
- console.log(arr.length);
The Object.keys() method will return an array of attribute names of all enumerable properties of a given object. The order of attribute names in the array is the same as that of traversing the object using the for in loop (the main difference between the two is that for in will also traverse the enumerable properties an object inherits from its prototype chain).