JS 計算一個物件/Object的長度
阿新 • • 發佈:2019-02-12
在我們日常開發中,物件的使用頻率很高,我們計算陣列的長度是非常方便的,但是如何計算物件的長度呢?
假如我們有一個圖書館的專案,專案中有一組圖書和作者,像下面這樣:
- 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"
- };
我們分析現在的需求,我們給一個API傳送資料,但是書的長度不能超過100,因此我們需要在傳送資料之前計算在一個物件中總共有多少本書。那麼我們總怎麼做呢?我們可能會這樣做:
[javascript] view plain copy- 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"
- "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);
下面我們來對陣列使用keys方法:
[javascript] view plain copy
- var arr = ["zuojj", "benjamin", "www.zuojj.com"];
- //Outputs: ["0", "1", "2"]
- console.log(Object.keys(arr));
- //Outputs: 3
- console.log(arr.length);
Object.keys() 方法會返回一個由給定物件的所有可列舉自身屬性的屬性名組成的陣列,陣列中屬性名的排列順序和使用for-in迴圈遍歷該物件時返回的順序一致(兩者的主要區別是 for-in 還會遍歷出一個物件從其原型鏈上繼承到的可列舉屬性)。