I am writing a function that iterates through all of the members of an array that are passed in as a parameter to the function. Each member of the array would be output to the console.
And then I need to expand on that function so that it will work whether an ARRAY or an OBJECT is passed in as the parameter to the function. This means I need to know how to distinguish whether or not the parameter is an ARRAY or an OBJECT.
Currently I am using a for loop and I created a forEach version too for variation.
See my codes:
function iterateMembers(arg){
for(let i = 0; i < arg.length; i++){
console.log(arg[i]);
}
}
let output = iterateMembers(arr);
console.log(output);
// forEach Version
function iterateMembers(arg){
arg.forEach((item) => console.log(item));
}
let arr = ['nci', 12, 'blog', 15];
let obj = {
firstname: 'nci',
lastname: 'g',
age: 21
};
let output = iterateMembers(arr);
console.log(output);
One big problem here is that when I passed in the obj it will not return anything and will return an error on both ES5 and ES6 version. This should work whether an ARRAY or an OBJECT is passed in as the parameter to the function. This means I need to know how to distinguish whether or not the parameter is an ARRAY or an OBJECT.
Based on what it is then will need to handle them appropriately and output the contents of the array or object to the console. I need to create this function for both ES5 and ES6 version. Any idea what am I missing? How can I do that?