javascript对象中的元素数

时间:2022-08-22 14:12:29

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

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

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:
I'm talking about the Object object (not objects in general):

编辑:我在谈论Object对象(一般不是对象):

var obj = new Object ;

7 个解决方案

#1


122  

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

尽管JS实现可能会在内部跟踪这样的值,但是没有标准的方法来实现它。

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

在过去,Mozilla的Javascript变体暴露了非标准__count__,但它已被1.8.5版本删除。

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

对于跨浏览器脚本编写,您将无法显式迭代属性并检查hasOwnProperty():

function countProperties(obj) {
    var count = 0;

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

    return count;
}

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

在支持ECMAScript 5的情况下,这也可以写成(Kudos to Avi Flax)

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

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

请记住,您还会错过不可枚举的属性(例如数组的长度)。

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.

如果您使用的是jQuery,Prototype,Mootools等框架,那么最新的炒作,请检查它们是否带有自己的集合API,这可能是比使用本机JS对象更好的解决方案。

#2


66  

To do this in any ES5-compatible environment

要在任何兼容ES5的环境中执行此操作

Object.keys(obj).length

(Browser support from here)
(Doc on Object.keys here, includes method you can add to non-ECMA5 browsers)

(此处的浏览器支持)(此处的Object.keys上的文档,包括可以添加到非ECMA5浏览器的方法)

#3


13  

if you are already using jQuery in your build just do this:

如果您已在构建中使用jQuery,请执行以下操作:

$(yourObject).length

It works nicely for me on objects, and I already had jQuery as a dependancy.

它对我的对象很好用,我已经把jQuery作为一个依赖。

#4


6  

function count(){
    var c= 0;
    for(var p in this) if(this.hasOwnProperty(p))++c;
    return c;
}

var O={a: 1, b: 2, c: 3};

count.call(O);

#5


2  

AFAIK, there is no way to do this reliably, unless you switch to an array. Which honestly, doesn't seem strange - it's seems pretty straight forward to me that arrays are countable, and objects aren't.

AFAIK,除非你切换到阵列,否则没有办法可靠地做到这一点。老实说,这看起来并不奇怪 - 对我来说,数组是可数的,而对象则不是。

Probably the closest you'll get is something like this

可能你得到的最接近的是这样的

// Monkey patching on purpose to make a point
Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this ) i++;
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 3

But this creates problems, or at least questions. All user-created properties are counted, including the _length function itself! And while in this simple example you could avoid it by just using a normal function, that doesn't mean you can stop other scripts from doing this. so what do you do? Ignore function properties?

但这会产生问题,或者至少会产生问题。计算所有用户创建的属性,包括_length函数本身!虽然在这个简单的例子中你可以通过使用普通函数来避免它,但这并不意味着你可以阻止其他脚本这样做。所以你会怎么做?忽略功能属性?

Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this )
  {
      if ( 'function' == typeof this[p] ) continue;
      i++;
  }
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 2

In the end, I think you should probably ditch the idea of making your objects countable and figure out another way to do whatever it is you're doing.

最后,我认为你应该放弃让你的对象可数的想法,并找出另一种方法去做你正在做的事情。

#6


1  

The concept of number/length/dimensionality doesn't really make sense for an Object, and needing it suggests you really want an Array to me.

数字/长度/维度的概念对于一个对象并没有真正意义,并且需要它表明你真的想要一个数组给我。

Edit: Pointed out to me that you want an O(1) for this. To the best of my knowledge no such way exists I'm afraid.

编辑:向我指出你想要一个O(1)。据我所知,恐怕不存在这样的方式。

#7


0  

You can use:

您可以使用:

({ foo:55, bar:99 }).__count__ // is: 2

has been taken from here

已被从这里带走

#1


122  

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

尽管JS实现可能会在内部跟踪这样的值,但是没有标准的方法来实现它。

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

在过去,Mozilla的Javascript变体暴露了非标准__count__,但它已被1.8.5版本删除。

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

对于跨浏览器脚本编写,您将无法显式迭代属性并检查hasOwnProperty():

function countProperties(obj) {
    var count = 0;

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

    return count;
}

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

在支持ECMAScript 5的情况下,这也可以写成(Kudos to Avi Flax)

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

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

请记住,您还会错过不可枚举的属性(例如数组的长度)。

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.

如果您使用的是jQuery,Prototype,Mootools等框架,那么最新的炒作,请检查它们是否带有自己的集合API,这可能是比使用本机JS对象更好的解决方案。

#2


66  

To do this in any ES5-compatible environment

要在任何兼容ES5的环境中执行此操作

Object.keys(obj).length

(Browser support from here)
(Doc on Object.keys here, includes method you can add to non-ECMA5 browsers)

(此处的浏览器支持)(此处的Object.keys上的文档,包括可以添加到非ECMA5浏览器的方法)

#3


13  

if you are already using jQuery in your build just do this:

如果您已在构建中使用jQuery,请执行以下操作:

$(yourObject).length

It works nicely for me on objects, and I already had jQuery as a dependancy.

它对我的对象很好用,我已经把jQuery作为一个依赖。

#4


6  

function count(){
    var c= 0;
    for(var p in this) if(this.hasOwnProperty(p))++c;
    return c;
}

var O={a: 1, b: 2, c: 3};

count.call(O);

#5


2  

AFAIK, there is no way to do this reliably, unless you switch to an array. Which honestly, doesn't seem strange - it's seems pretty straight forward to me that arrays are countable, and objects aren't.

AFAIK,除非你切换到阵列,否则没有办法可靠地做到这一点。老实说,这看起来并不奇怪 - 对我来说,数组是可数的,而对象则不是。

Probably the closest you'll get is something like this

可能你得到的最接近的是这样的

// Monkey patching on purpose to make a point
Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this ) i++;
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 3

But this creates problems, or at least questions. All user-created properties are counted, including the _length function itself! And while in this simple example you could avoid it by just using a normal function, that doesn't mean you can stop other scripts from doing this. so what do you do? Ignore function properties?

但这会产生问题,或者至少会产生问题。计算所有用户创建的属性,包括_length函数本身!虽然在这个简单的例子中你可以通过使用普通函数来避免它,但这并不意味着你可以阻止其他脚本这样做。所以你会怎么做?忽略功能属性?

Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this )
  {
      if ( 'function' == typeof this[p] ) continue;
      i++;
  }
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 2

In the end, I think you should probably ditch the idea of making your objects countable and figure out another way to do whatever it is you're doing.

最后,我认为你应该放弃让你的对象可数的想法,并找出另一种方法去做你正在做的事情。

#6


1  

The concept of number/length/dimensionality doesn't really make sense for an Object, and needing it suggests you really want an Array to me.

数字/长度/维度的概念对于一个对象并没有真正意义,并且需要它表明你真的想要一个数组给我。

Edit: Pointed out to me that you want an O(1) for this. To the best of my knowledge no such way exists I'm afraid.

编辑:向我指出你想要一个O(1)。据我所知,恐怕不存在这样的方式。

#7


0  

You can use:

您可以使用:

({ foo:55, bar:99 }).__count__ // is: 2

has been taken from here

已被从这里带走