Efficiently counting the number of keys / properties of an Object in JavaScript

前端 未结 3 689
夕颜
夕颜 2021-02-07 02:29

This question is almost identical to How to efficiently count the number of keys/properties of an object in JavaScript?.

I want to know one extra piece of information: w

相关标签:
3条回答
  • 2021-02-07 03:11

    See the source, specifically GetLocalElementKeys

    v8 objects.cc

    0 讨论(0)
  • 2021-02-07 03:29

    After a bit of research, there is no way to determine the number of keys in a JavaScript Object in constant time, at least not in Node... and not quite yet. Node internally keeps track of this information, but it does not expose it, since there is no method to do so in ECMA-262 5th.

    It's worth noting that Harmony (ECMA version 6) may natively support Maps and Sets. Not sure what the spec for these will turn out to be.

    I am told that we need to bring this up with TC39 committee.

    Bug report for V8: http://code.google.com/p/v8/issues/detail?id=1800

    0 讨论(0)
  • 2021-02-07 03:34

    ECMA 6 harmony introduces Map and Set classes which you can probably utilize (in the future :)

    var map = new Map;
    map.set('a', 'b');
    console.log(map.size); // prints 1
    

    I believe it should have complexity O(1), not tried though. You can run it in node 0.11+ via node --harmony script.js.


    Another way is to use Proxy class which also has been added in harmony.

    0 讨论(0)
提交回复
热议问题