Skip to content

Instantly share code, notes, and snippets.

@FlorianH
Created April 27, 2021 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FlorianH/50986892d62f78fd0bcdb0ceba9c5bff to your computer and use it in GitHub Desktop.
Save FlorianH/50986892d62f78fd0bcdb0ceba9c5bff to your computer and use it in GitHub Desktop.
function each(objOrArr, callback) {
/* Test to see if the argument is an array first since `typeof` does not
distinguish between arrays and plain objects. */
if (Array.isArray(objOrArr)) {
/* The `forEach` method of arrays does exactly what we want. The
function you pass to it is called for each item in the array and is
passed the item and its index. */
objOrArr.forEach(callback);
} else {
/* If the argument is not an array, assume that it is an object and
loop through all of its properties. */
for (var key in objOrArr) {
/* The `key` variable is now set to the name of the current
property in the loop. We can now use `key` to access the value
of the current property in the loop and pass that value, along
with the key, to the callback function. */
callback(objOrArr[key], key);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment