Created
April 19, 2013 08:38
-
-
Save luckyshot/5418978 to your computer and use it in GitHub Desktop.
JavaScript array loops
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
// With for..in | |
var stuff, key; | |
stuff = []; | |
stuff[0] = "zero"; | |
stuff[9999] = "nine thousand nine hundred and ninety-nine"; | |
stuff.name = "foo"; | |
for (key in stuff){ | |
if (stuff.hasOwnProperty(key) && String(Number(key)) === key) { | |
console.log("stuff[" + key + "] = " + stuff[key]); | |
} | |
} | |
// With forEach (ECMAScript 5+) | |
var stuff; | |
stuff = []; | |
stuff[0] = "zero"; | |
stuff[9999] = "nine thousand nine hundred and ninety-nine"; | |
stuff.name = "foo"; | |
stuff.forEach(function(value, key) { | |
console.log("stuff[" + key + "] = " + value); | |
}); | |
// Source: http://blog.niftysnippets.org/2010/11/myths-and-realities-of-forin.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment