简体   繁体   中英

Why this code is showing me undefined and type error?

This code is showing error and giving me undefined can anyone pls give me logic for this:

 const data = ['1','2','3','4','6']; const consoleItem = (item, index,arr) =>{ console.log(item); console.log(index); console.log(arr); } data.forEach(consoleItem())

Your syntax was incorrect. The way you have it setup, it only calls consoleItem once and it calls it with no parameters, and the return value is used as a parameter to foreach .

The way I am using it below, consoleItem is acting as a callback to the forEach method and I am passing it the three parameters implicitly given by each iteration of the forEach method.

Try it like this.

 const data = ['1','2','3','4','6']; const consoleItem = (item, index,arr) =>{ console.log(item); console.log(index); console.log(arr); } data.forEach(consoleItem) //data.forEach((x,y,z) => {consoleItem(x,y,z)}) Same as above

The function forEach require a function definition, but you are invoking the function in forEach it self you can use something like this

 const data = ['1','2','3','4','6']; const consoleItem = (item, index,arr) =>{ console.log(item); console.log(index); console.log(arr); } data.forEach(consoleItem)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM