Object.prototype.hasOwnProperty.call()计算js对象的长度

来源:互联网 发布:用vb制作倒计时 编辑:程序博客网 时间:2024/05/17 01:01

在我们日常开发中,对象的使用频率很高,我们计算数组的长度是非常方便的,但是如何计算对象的长度呢?
假如我们有一个图书馆的项目,项目中有一组图书和作者,像下面这样:

[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  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
 在CODE上查看代码片派生到我的代码片
  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.   
  11. var bookCount = countProperties(bookAuthors);  
  12.   
  13. // Outputs: 4  
  14. console.log(bookCount);  


这是可以实现的,幸运的是Javascript提供了一个更改的方法来计算对象的长度:

[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  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.   
  9. //Outputs: Array [ "Farmer Giles of Ham", "Out of the Silent Planet", "The Place of the Lion", "Poetic Diction" ]  
  10. console.log(arr);  
  11.   
  12. //Outputs: 4  
  13. console.log(arr.length);  

下面我们来对数组使用keys方法:

[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. var arr = ["zuojj""benjamin""www.zuojj.com"];  
  2.   
  3. //Outputs: ["0", "1", "2"]  
  4. console.log(Object.keys(arr));  
  5.   
  6. //Outputs: 3  
  7. console.log(arr.length);  

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


阅读全文
0 0