Length of a JavaScript object

前端 未结 30 3760
我在风中等你
我在风中等你 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 05:11

    I'm not a JavaScript expert, but it looks like you would have to loop through the elements and count them since Object doesn't have a length method:

    var element_count = 0;
    for (e in myArray) {  if (myArray.hasOwnProperty(e)) element_count++; }
    

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

提交回复
热议问题