Length of a JavaScript object

前端 未结 30 3067
我在风中等你
我在风中等你 2020-11-21 04:35

I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object?

const myObject = new Object();
myObject["         


        
30条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 04:55

    @palmsey: In fairness to the OP, the JavaScript documentation actually explicitly refer to using variables of type Object in this manner as "associative arrays".

    And in fairness to @palmsey he was quite correct. They aren't associative arrays; they're definitely objects :) - doing the job of an associative array. But as regards to the wider point, you definitely seem to have the right of it according to this rather fine article I found:

    JavaScript “Associative Arrays” Considered Harmful

    But according to all this, the accepted answer itself is bad practice?

    Specify a prototype size() function for Object

    If anything else has been added to Object .prototype, then the suggested code will fail:

    
    

    I don't think that answer should be the accepted one as it can't be trusted to work if you have any other code running in the same execution context. To do it in a robust fashion, surely you would need to define the size method within myArray and check for the type of the members as you iterate through them.

提交回复
热议问题