简体   繁体   English

JavaScript 回调 function 返回未定义

[英]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.一个包含带有forEach方法的数组元素,另一个是回调 function,它从第一个 function 访问数组元素并log它们的长度。 The second function is not working and throws Uncaught ReferenceError .第二个 function 不工作并抛出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 ?我该如何解决这个error and access the length of elements in my callback function , any help will be appreciated并在我的callback function中访问元素的length ,任何帮助将不胜感激

You're trying to call a function using an array as prop您正在尝试使用数组作为道具调用 function

 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. allFruits是 listFruits function 中的局部变量,在listFruits之外无法访问。

Instead, countFruits should take its own allFruits parameter.相反, countFruits应该采用自己的allFruits参数。 Then it can call the callback function, passing allFruits.length to get it logged.然后它可以调用回调 function,传递allFruits.length以使其记录。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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