1. 程式人生 > >JS 計算一個物件/Object的長度

JS 計算一個物件/Object的長度

在我們日常開發中,物件的使用頻率很高,我們計算陣列的長度是非常方便的,但是如何計算物件的長度呢?
假如我們有一個圖書館的專案,專案中有一組圖書和作者,像下面這樣:

[javascript] view plain copy
  1. var bookAuthors = {  
  2.     "Farmer Giles of Ham""J.R.R. Tolkien",  
  3.     "Out of the Silent Planet""C.S. Lewis",  
  4.     "The Place of the Lion""Charles Williams",  
  5.     "Poetic Diction""Owen Barfield"
  6. };  

我們分析現在的需求,我們給一個API傳送資料,但是書的長度不能超過100,因此我們需要在傳送資料之前計算在一個物件中總共有多少本書。那麼我們總怎麼做呢?我們可能會這樣做:

[javascript] view plain copy
  1. function countProperties (obj) {  
  2.     var count = 0;  
  3.     for (var property in obj) {  
  4.         if (Object.prototype.hasOwnProperty.call(obj, property)) {  
  5.             count++;  
  6.         }  
  7.     }  
  8.     return count;  
  9. }  
  10. var bookCount = countProperties(bookAuthors);  
  11. // Outputs: 4
  12. console.log(bookCount);  
這是可以實現的,幸運的是Javascript提供了一個更改的方法來計算物件的長度:[javascript] view plain copy
  1. var bookAuthors = {  
  2.     "Farmer Giles of Ham""J.R.R. Tolkien",  
  3.     "Out of the Silent Planet""C.S. Lewis",  
  4.     "The Place of the Lion"
    "Charles Williams",  
  5.     "Poetic Diction""Owen Barfield"
  6. };  
  7. var arr = Object.keys(bookAuthors);  
  8. //Outputs: Array [ "Farmer Giles of Ham", "Out of the Silent Planet", "The Place of the Lion", "Poetic Diction" ]
  9. console.log(arr);  
  10. //Outputs: 4
  11. console.log(arr.length);  

下面我們來對陣列使用keys方法:
[javascript] view plain copy
  1. var arr = ["zuojj""benjamin""www.zuojj.com"];  
  2. //Outputs: ["0", "1", "2"]
  3. console.log(Object.keys(arr));  
  4. //Outputs: 3
  5. console.log(arr.length);  

Object.keys() 方法會返回一個由給定物件的所有可列舉自身屬性的屬性名組成的陣列,陣列中屬性名的排列順序和使用for-in迴圈遍歷該物件時返回的順序一致(兩者的主要區別是 for-in 還會遍歷出一個物件從其原型鏈上繼承到的可列舉屬性)。