什么是“<ref *1>”?

What's a "<ref *1>"?

根据主题,我在互联网上找不到任何关于此的具体信息。

即使我将 属性 称为“树”,但在 class 名称之前得到的输出中的 <ref *1> 是什么?参考...什么,为什么我调用 属性?以及如何修复它?

CLI 输出:

> $ node binary-search-tree.js                                                                                                                                  
<ref *1> BinarySearchTree { tree: [Circular *1] }

这是我的代码(学习算法):

const addNode = (base, num) => {
  // base = {number, left?, right?}
  if (num <= base.number) {
    if (base.left) {
      base.left = addNode(base.left, num);
    } else base.left = { number: num };
  }
  if (num > base.number) {
    if (base.right) {
      base.right = addNode(base.right, num);
    } else base.right = { number: num };
  }

  return base;
};

class BinarySearchTree {
  constructor(baseValue) {
    this.tree = { number: baseValue };
  }

  get data() {
    return this.tree;
  }

  get right() {
    throw new Error("Remove this statement and implement this function");
  }

  get left() {
    throw new Error("Remove this statement and implement this function");
  }

  insert(nums) {
    if (typeof nums === "number") {
      this.tree = addNode(this, nums);
      return;
    }
    for (let number of nums) {
      this.tree = addNode(this, number);
    }
  }

  each() {
    throw new Error("Remove this statement and implement this function");
  }
}

const lolTree = new BinarySearchTree(5);
lolTree.insert(58);
lolTree.insert([2, 7, 4, 100]);
lolTree.insert(55);

console.log(lolTree.tree);

这是显示 circular reference 的参考索引。

也就是说,你的对象中有一些圆形结构。

你也可以通过运行看到它是循环的:

JSON.stringify(lolTree.tree)

这将导致:

VM829:1 Uncaught TypeError: Converting circular structure to JSON --> starting at object with constructor 'BinarySearchTree' --- property 'tree' closes the circle at JSON.stringify ()

当对象的 属性 引用对象本身时,就会发生这种情况。考虑代码:

// define some object
const a = { foo: 1 };

// add a property referring to the object
a.bar = a;

console.log(JSON.stringify(a)); // TypeError

addNode 应该是:

const addNode = (base, num) => {
  // base = {number, left?, right?}
  if (num <= base.number) {
    if (base.left) {
       addNode(base.left, num);
    } else {
       base.left = { number: num };
    }
  }
  else {
    if (base.right) {
       addNode(base.right, num);
    } else {
       base.right = { number: num };
    }
  }
};

避免@aziza提到的循环引用;编辑:将第二个 if 更改为 else - 它要么在左边,要么在右边,所以如果它不在左边...

我觉得很蠢...我留下了 insert() 两个 this,而不是 this.tree。谢谢@Aziza 向我解释这个 <ref *1>