Skip to content

Instantly share code, notes, and snippets.

@luckyshot
Created April 19, 2013 08:38
Show Gist options
  • Save luckyshot/5418978 to your computer and use it in GitHub Desktop.
Save luckyshot/5418978 to your computer and use it in GitHub Desktop.
JavaScript array loops
// 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