Number of elements in a javascript object

后端 未结 6 2115
借酒劲吻你
借酒劲吻你 2020-12-12 17:46

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 retriev

6条回答
  •  醉梦人生
    2020-12-12 18:32

    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.

    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?

    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.

提交回复
热议问题