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

查看:28
本文介绍了如何计算 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?

推荐答案

没有简单的答案,因为 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");

第二行显示了其他代码如何向所有Object 派生类添加属性.如果删除循环内的 hasOwnProperty() 检查,则属性计数将至少增加到 4.代码还修改了 Object 原型.

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天全站免登陆