Going through some practice problems and can’t figure out how correctly callback. It returns "
let myForEach = function(array, cb) {
for (let j = 0; j < array.length; j++) {
cb(array[j])
}
};
myForEach(['a', 'b', 'c'], function(el, i) {
console.log(el + ' is at index ' + i);
});
// expected return "a is at index 1"
// actual return "a is at index undefined"
I tried to call i as an extra argument, and tried to use this.i, call it within the scope of the cb, all either return undefined or are ignored.
>Solution :
You can utilize the index for the callback by passing it in as a second argument:
let myForEach = function(array, cb) {
for (let j = 0; j < array.length; j++) {
cb(array[j], j)
}
};
myForEach(['a', 'b', 'c'], function(el, i) {
console.log(el + ' is at index ' + i);
});
// expected return "a is at index 0"
// actual return "a is at index 0"