如何计算JavaScript对象的属性? [英] How do I count a JavaScript object's attributes?

查看:145
本文介绍了如何计算JavaScript对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在JavaScript中有以下对象:

Suppose I have the following object in JavaScript:

var object = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}; 

如何找出对象中存在多少个值?

How do I find out how many values exist in the object?

推荐答案

没有简单的答案,因为对象— JavaScript中的每个对象都来源于—自动包含许多属性,您获得的确切属性集取决于特定的解释器以及在您之前执行的代码。所以,你不得不将你定义的那些与你免费获得的那些分开。

There's no easy answer, because Object — which every object in JavaScript derives from — includes many attributes automatically, and the exact set of attributes you get depends on the particular interpreter and what code has executed before yours. So, you somehow have to separate the ones you defined from those you got "for free."

这是一种方式:

var foo = {"key1": "value1", "key2": "value2", "key3": "value3"};
Object.prototype.foobie = 'bletch'; // add property to foo that won't be counted

var count = 0;
for (var k in foo) {
    if (foo.hasOwnProperty(k)) {
       ++count;
    }
}
alert("Found " + count + " properties specific to foo");

第二行显示其他代码如何为所有对象添加属性衍生品。如果在循环中删除 hasOwnProperty()检查,则属性计数将至少达到4.在包含除此代码之外的其他JavaScript的页面上,它可能更高4,如果其他代码也修改对象原型。

The second line shows how other code can add properties to all Object derivatives. If you remove the hasOwnProperty() check inside the loop, the property count will go up to at least 4. On a page with other JavaScript besides this code, it could be higher than 4, if that other code also modifies the Object prototype.

这篇关于如何计算JavaScript对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆