Skip to content

Instantly share code, notes, and snippets.

@kaiguogit
Last active August 25, 2016 06:42
Show Gist options
  • Save kaiguogit/828e0426cf814e3c8371bdc632d51a43 to your computer and use it in GitHub Desktop.
Save kaiguogit/828e0426cf814e3c8371bdc632d51a43 to your computer and use it in GitHub Desktop.
Javascript property enumeration

Q: Why don't have to write conditional statement to determine whether input is object or array? A: because Object.keys behave similarly when input is input or object, It returns an array of index when input is an array. See below example from MDN doc.

var arr = ['a', 'b', 'c']; console.log(Object.keys(arr)); // console: ['0', '1', '2']

function deepEach(obj, fn){
keys = Object.keys(obj);
keys.forEach(function(key){
if(typeof obj[key] === 'object')
deepEach(obj[key], fn);
else
fn(obj[key]);
});
}
deepEach(['H', {arr:['e'], str: 'l'}, 'l', [{letter: 'o'}]],console.log.bind(console));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment