Last active
August 29, 2015 13:56
-
-
Save blackmjck/8809617 to your computer and use it in GitHub Desktop.
Simple method for calculating the length of an associative array (i.e. object). Counts the first-level child properties only.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Object Size - a simple utility function for returning the length of an associative array (i.e. object) | |
* | |
* Counts the first-level direct child properties of the object and returns the count | |
* | |
* @author Steven Wiggins | |
* @date 2/4/2014 | |
* @version 0.2 | |
*/ | |
;(function() { | |
Object.prototype.size = function() { | |
var total = 0, prop; | |
// this becomes trivial if the engine supports the Object.keys() function | |
if( Object.keys ) { | |
return Object.keys( this ).length; | |
} | |
// otherwise, we do it the old-fashioned way | |
for( prop in this ) { | |
this.hasOwnProperty( prop ) && total++; | |
} | |
return total; | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment