[英]Cannot read property 'push' of undefined when when using nested functions
Why does the following code work为什么下面的代码有效
const inorderTraversal = (root) => {
let out = []
const traverse = (node) => {
console.log(node)
if (!node) return
traverse(node.left)
out.push(node.val)
traverse(node.right)
}
traverse(root)
return out
};
but this one does not但这个没有
const inorderTraversal = (root) => {
let out = []
const traverse = (node,arr) => {
if (!node) return
traverse(node.left)
arr.push(node.val)
traverse(node.right)
}
traverse(root,out)
return out
};
I need to modify the algorithm for multiple binary trees but when sending the array as a parameter instead of a global variable I get an Cannot read property 'push' of undefined
error.我需要修改多个二叉树的算法,但是当将数组作为参数而不是全局变量发送时,我得到了
Cannot read property 'push' of undefined
错误的Cannot read property 'push' of undefined
。
In your second second script, you wrote traverse(node.right)
, but, because your traverse
function now has two parameters and you only pass in one, arr
is undefined.在第二个脚本中,您编写了
traverse(node.right)
,但是,因为您的traverse
函数现在有两个参数,而您只传入一个参数,所以arr
未定义。 Then, in the recursive function call, you get a warning on the statement arr.push(node.val)
because you are trying to call the push
method on arr
even though the variable is undefined.然后,在递归函数调用中,您会收到关于
arr.push(node.val)
语句的警告,因为您试图在arr
上调用push
方法,即使该变量未定义。 To fix the error, add arr
as the second parameter of the function call.要修复错误,请添加
arr
作为函数调用的第二个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.