javascript - TypeError:无法读取未定义的属性“数据”-但已定义
问题描述
我正在研究二叉搜索树算法,由于某种原因,我不断收到类型错误。它总是在将第二个值插入树时发生。特别是当当前节点的值与传入的数据值进行比较时
这是代码:
class Node {
constructor(data, left = null, right = null) {
this.data = data;
this.leftNode = left;
this.rightNode = right;
}
}
class BST {
constructor() {
this.root = null;
}
insert(data) {
const dataNode = new Node(data);
if (this.root === null) {
this.root = dataNode;
} else {
let currentNode = this.root;
let parentNode;
while (true) {
parentNode = currentNode;
if (data < currentNode.data) {
currentNode = parentNode.left;
if (parentNode.left === null) {
parentNode.left = dataNode
break;
}
} else {
currentNode = parentNode.right
if (parentNode.right === null) {
parentNode.right = dataNode
break;
}
}
}
}
}
}
const bst = new BST();
bst.insert(10);
bst.insert(5);
bst.insert(6);
bst.insert(8);
bst.insert(12);
bst.insert(7);
bst.insert(7);
这是错误:
Uncaught TypeError: Cannot read property 'data' of undefined
at BST.insert (<anonymous>:22:32)
at <anonymous>:42:5
解决方案
你正在做parentNode.left
的是undefined
你应该做的parentNode.leftNode
推荐阅读
- security - 他们是否有任何安全、强大的工具可用于执行芹菜任务的监控和通知警报?
- java - 将自定义 Confluence 插件从版本 5 升级到 7+
- android - 如何使用隐藏代码在两家公司之间共享应用程序开发?
- c - 凯撒加密但输出错误
- node.js - Mongoose.connect 未连接到本地数据库
- swiftui - 如何重新渲染 UI 以响应埋在嵌套类中的计算属性?
- javascript - getUserMedia 约束禁用我的相机
- javascript - 得到结果 Promise {
使用 d3.csv 异步函数后 - boost - 找不到Boost(缺少:python3)(找到版本“1.76.0”)-CMake Windows
- ansible - boto 没有在 ansible amazon.aws.ec2 模块中获取 ~/.aws/config