简体   繁体   English

使用嵌套函数时无法读取未定义的属性“推送”

[英]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.

相关问题 错误:在存储在对象中的空数组上使用.push时,无法读取未定义的属性推送 - Error: cannot read property push of undefined when using .push on an empty array that is stored in an object 发布到firebase时,Angular无法读取未定义的属性推送 - Angular cannot read property push of undefined when posting to firebase 初始化数组时无法读取未定义的属性“推送” - Cannot read property 'push' of undefined when i initialized the array 组合数组时无法读取未定义的属性“推送” - Cannot read property 'push' of undefined when combining arrays 使用 angular 5 在 Firebase 中存储数据时无法读取未定义的属性“推送” - Cannot read property 'push' of undefined when using angular 5 to store data in firebase 绑定2个函数时无法读取未定义的属性“ bind” - Cannot read property 'bind' of undefined when binding 2 functions 返回嵌套的Promise时无法读取未定义的属性'then' - Cannot read property 'then' of undefined when returning nested promise 无法使用localStorage读取未定义的属性推送 - Cannot read property push of undefined using localStorage 当我需要将项目推送到接口的属性之一时,无法读取未定义的属性“推送” - Cannot read property 'push' of undefined when i need push item to one of property of interface TypeError 'Cannot read property/undefined' 使用 toString 属性时 - TypeError 'Cannot read property/undefined ' when using toString property
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM