javascript - Node : how to put objects as keys of hash object?

标签 javascript node.js

请看下面的代码片段:

class Node {
    constructor(num) {
        this.num = num;
        this.right = null;
        this.left = null;
    }
}

let node1 = new Node(1);
let node2 = new Node(2);
let hash = {};
hash[node1] = 1;
console.log(hash[node2]);  // prints "1" ????

为什么 hash[node2] 返回值 1? 哈希中只存储了node1...

最佳答案

如果你记录你的对象,你会得到这个:

{ '[对象对象]': 1 }

因此,为什么下面记录 1,因为 node2 被解释为 [object Object]

console.log(hash[node2]); //This is evaluating hash['object Object'] (Again)

要解决这个问题,有多种方法,一种是使用 JSON API 将您的对象字符串化,然后使用返回值作为键。

例如

hash[JSON.stringify(node1)] = 1;

现在你拥有的是:

{'{"num":1,"right":null,"left":null}': 1 }

因此,正如预期的那样,访问 hash[node2] 现在将是未定义的。

hash[node2] === undefined; //true
hash[JSON.stringify(node2)] === undefined; //true

您可能想围绕此创建一个小 API。作为一个非常粗略的例子:

class Hash {

    constructor () {
        this.hashes = {};
    }

    get (key) {
        return this.hashes[JSON.stringify(key)];
    }

    set (key, value) {
        this.hashes[JSON.stringify(key)] = value;
    }
}

const hashStore = new Hash();

hashStore.set({foo: 'bar'}, 1);

hashStore.set({foo: 'cheese'}, 2);

console.log(hashStore.get({foo: 'bar'})); // 1
console.log(hashStore.get({foo: 'cheese'})); //2

或者,如果您仅将对象用作“您控制”的键,那么正如 Jakub Keller 在他的回答中指出的那样,您可以覆盖 Node 类的 toString 函数。

这两种方法的回退是“唯一性”,对于任何一种方法都是稳定的方法,您需要为每个对象引入一个唯一的键,如果您采用 Jakub Keller 的方法,您将使用该唯一键在 toString 覆盖中。

这两种方法都满足一组需求,如果您要存储文字,一组不同的对象作为您的键,我可能会采用我的方法,并让 API 将自定义的唯一 ID 写入每个存储的对象在 get 方法中,同样不完美,因为您可以覆盖现有 key 。

关于javascript - Node : how to put objects as keys of hash object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52118024/

相关文章:

node.js - 如何在 Jelastic 云中启动 Node.js 应用程序

javascript - 错误:在为我的 typescript 应用程序配置Webpack时无法解析"file"或“目录”

ASP.NET - 使用 jQuery 处理基于 JSON 的 Web 服务的正确方法是什么?

mysql - 从多个表中提取 Sequelize 信息

c++ - 使用 NAN 在 Node.js 的 C++ 模块中未调用 SetAccessor 函数

node.js - 是否可以自动安装 node.js 脚本所需的模块?

javascript - 从元素中选择 img

javascript - Angular 6 服务和类继承

javascript - 为什么Vue实例的数据没有更新

node.js - 警告 : NODE_ENV value of 'test ' did not match any deployment config file names