Created
April 27, 2021 17:05
-
-
Save FlorianH/50986892d62f78fd0bcdb0ceba9c5bff to your computer and use it in GitHub Desktop.
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
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