简体   繁体   中英

JavaScript callback function return undefined

I am trying to write two functions. One contains elements of array with forEach method and another is a callback function that access elements of array from the first function and log their length. The second function is not working and throws Uncaught ReferenceError . I wonder why I get this error.

 const fruits = ["Banana", "Mango", "Apple"]; fruits.forEach(listFruits); function listFruits(allFruits) { console.log(allFruits); } function countFruits(callback) { callback(allFruits); console.log(allFruits.length); } countFruits(listFruits);

how can i fix this error ? and access the length of elements in my callback function , any help will be appreciated

You're trying to call a function using an array as prop

 const fruits = ["Banana", "Mango", "Apple"]; fruits.forEach(listFruits); function listFruits(allFruits) { console.log(allFruits); } function countFruits(callback) { // the following line is the problem, "allFruits" are not defined. // if you change the prop to the array "fruits" the error is solved callback(fruits); console.log(fruits.length); } countFruits(listFruits);

allFruits is a local variable in the listFruits function, you can't access it outside the function.

Instead, countFruits should take its own allFruits parameter. Then it can call the callback function, passing allFruits.length to get it logged.

 const fruits = ["Banana", "Mango", "Apple"]; fruits.forEach(listFruits); function listFruits(allFruits) { console.log(allFruits); } function countFruits(callback, allFruits) { callback(allFruits.length); } countFruits(listFruits, fruits);

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