JavaScript literal object length === undefined?

I am working on this animation function , but I have a problem. I cannot imagine what should be an easy task; I cannot get the length of an object. If you notice that jsFiddle you see that I run alert(properties.length); , and it returns undefined . Can anyone understand why this could be?

+37
javascript object properties object-literal
Jan 14 '11 at 11:25
source share
5 answers

The JavaScript object simply does not have a length property, only Arrays . If you want to know the number of properties that are defined on an object, you must iterate over them and read them.

Also, your for in loop is prone to errors related to the Object.prototype extension, as it will go through a prototype chain and lists all the properties that are on the chain.

Example

 // Poisoning Object.prototype Object.prototype.bar = 1; var foo = {moo: 2}; for(var i in foo) { console.log(i); // logs both 'moo' AND 'bar' } 

You must use the hasOwnProperty method of the object to filter out these unwanted properties.

 // still the foo from above for(var i in foo) { if (foo.hasOwnProperty(i)) { console.log(i); // only logs 'moo' } } 

Many JavaScript frameworks there extend the prototype, and without using hasOwnProperty , often lead to terrible errors.

Update

Regarding the real problem, that your code is not an animation of both properties.

 for(var p in properties) { ... for(var i = 0; i <= frames; i++) { setTimeout((function(exti, element) { return function() { // p gets overriden by for outer for in loop element.style[p] = original + (pixels * exti) + 'px'; } // you need to pass in a copy of the value of p here // just like you do with i and element })(i, element), i * (1000 / 60), element); } .... } 
+40
Jan 14 '11 at 11:31
source share

This is supported in node.js and newer environments.

 var obj = {a: "a", b: "b"}; Object.keys(obj).length // 2 
+41
Mar 06 '12 at 17:58
source share

If you are using Underscore.js , you can use _.size() :

 _.size({one : 1, two : 2, three : 3}); => 3 
+11
Mar 06 2018-12-12T00:
source share

Objects have no length, you will need to use an array if you want to.

If you need to find the number of properties in an object, then there is only one way:

 var length =0; for(var i in obj) length++; 
0
Jan 14 '11 at 11:30
source share

Here @Junaid Qadir Shekhanzai is a generic function for "finding the length of an object" (which, as we were told, is properly called "counting the properties of an object"). It combines solutions from @Ivo Wetzel and @Martin Jespersen:

 function countProperties(myObj){ var length = 0; if(typeof myObj != 'object'){ return false; } for(var i in myObj) { length++; } return length; } 
0
Oct 31 '17 at 21:49
source share



All Articles