JavaScript - Using the for-in loop
// JavaScript - Using the for-in loop:
The for-in loop:
for (variable name in object){
...
}
is used to iterate over properties of an object. In each repetition, one
property from the object is associated to the variable name, and the loop is
continued till all the properties of the object has been processed.
It is usually necessary to test use object.hasOwnProperty(variable) to determine
whether the property name is truly a member of the object or was found instead
on the prototype chain.
for (myvar in obj) {
if (obj.hasOwnProperty(myvar)) {
...
}
}
// Counting the number of elements in an associative array:
Object.keys(counterArray).length
We can also calculate the length of an object by iterating through an object
and by counting the object's own property.
function getSize(object){
var count = 0;
for(key in object){
// hasOwnProperty method check own property of object
if(object.hasOwnProperty(key)) count++;
}
return count;
}
page revision: 2, last edited: 14 Nov 2016 18:20





