JavaScript对象中的元素数 [英] Number of elements in a javascript object

查看:159
本文介绍了JavaScript对象中的元素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法来获取(从某个地方)javascript对象中的元素数量? (即恒定时间复杂性)。

Is there a way to get (from somewhere) the number of elements in a javascript object?? (i.e. constant-time complexity).

我找不到检索该信息的属性或方法。到目前为止,我只能想到在整个集合中进行迭代,但这是线性时间。

奇怪的是,没有对对象的大小的直接访问,你不认为。

I cant find a property or method that retrieve that information. So far I can only think of doing an iteration through the whole collection, but that's linear time.
It's strange there is no direct access to the size of the object, dont you think.

EDIT:

我在谈论 Object 一般来说):

var obj = new Object ;


推荐答案

虽然JS实现可能在内部跟踪这样的值

Although JS implementations might keep track of such a value internally, there's no standard way to get it.

过去,Mozilla的Javascript变体暴露了非标准 __ count __ , 1.8.5。

In the past, Mozilla's Javascript variant exposed the non-standard __count__, but it has been removed with version 1.8.5.

对于跨浏览器脚本,你需要显式地遍历属性并检查 hasOwnProperty()

For cross-browser scripting you're stuck with explicitly iterating over the properties and checking hasOwnProperty():

function countProperties(obj) {
    var count = 0;

    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            ++count;
    }

    return count;
}

在ECMAScript 5能够实现的情况下,这也可以写成到 Avi Flax

In case of ECMAScript 5 capable implementations, this can also be written as (Kudos to Avi Flax)

function countProperties(obj) {
    return Object.keys(obj).length;
}

请记住,您也会错过不可枚举的属性例如数组的 length )。

Keep in mind that you'll also miss properties which aren't enumerable (eg an array's length).

如果你使用一个框架像jQuery,Prototype,Mootools,$ whatever -the-newest-hype,检查他们是否有自己的集合API,这可能是一个比使用原生JS对象更好的解决你的问题的方法。

If you're using a framework like jQuery, Prototype, Mootools, $whatever-the-newest-hype, check if they come with their own collections API, which might be a better solution to your problem than using native JS objects.

这篇关于JavaScript对象中的元素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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