Get the object length in angularjs is undefined

后端 未结 8 2257
梦谈多话
梦谈多话 2021-02-19 03:57

How can I get the object length ?

In console my object looks like this:

Object {
 2: true,
 3: true,
 4: true
}

.length w

8条回答
  •  梦如初夏
    2021-02-19 04:31

    You don't want to repeat that Object.keys(obj) everywhere you want to get the length, as the code might get pretty messy. Therefore just put it in some personal project snippet library to be available across the site:

    Object.prototype.length = function(){
        return Object.keys(this).length
    }
    

    and than when you need to know object 's length you can run

    exampleObject.length()
    

    there's one problem with above, if you create an object that would have a "length" key, you will break the "prototype" function:

    exampleObject : { length: 100, width: 150 } 
    

    but you can use your own synonym for length, like "l()" instead of "length()"

提交回复
热议问题