Javascript Map返回undefined虽然定义了(key,value)对

时间:2018-03-22 18:10:26

标签: javascript node.js

我正在使用nodejs在linux终端中运行此代码片段。虽然正确设置了(键,值)对,但代码打印未定义。对此问题有任何解释或解决方法吗?

function trial() {
    var obj1 = {};
    var obj2 = {};
    obj1.fund = 1;
    obj1.target = 2;
    obj2.fund = 1;
    obj2.target = 2;
    states = [];
    states.push(obj1);
    states.push(obj2);
    actions = [1,2,3,4];
    table = new Map();
    for (var state of states) {
        for (var action of actions) {
            cell = {};
            cell.state = state;
            cell.action = action;
            table.set(cell, 0);
        }
    }
    var obj = {};
    obj.state = states[1];
    obj.action = actions[1];
    console.log(table.get(obj));   
}

2 个答案:

答案 0 :(得分:1)

您需要原始对象引用以匹配表中的键(Map()),让我们保存每个新的cell,这是每个对象引用以显示该内容。

即使你有一个深层克隆的对象,Map(),它也不是同一个密钥。

     var obj1 = {};
     var obj2 = {};
     obj1.fund = 1;
     obj1.target = 2;
     obj2.fund = 1;
     obj2.target = 2;
     states = [];
     states.push(obj1);
     states.push(obj2);
     actions = [1,2,3,4];
     table = new Map();
     var objRefs = [];
     var count = 0;
     for (var state of states) {
         for (var action of actions) {
             cell = {};
             cell.state = state;
             cell.action = action;
             table.set(cell, count);
             objRefs.push(cell);  //hold the object reference
             count ++;
         }
     }
     
     for (var i = 0; i < objRefs.length; i++) {
       console.log(table.get(objRefs[i]));
     }

     // Copy by reference
     var pointerToSecondObj = objRefs[1]; 
     
     console.log(table.get(pointerToSecondObj));
     
     //Deep clone the object
     var deepCloneSecondObj =  JSON.parse(JSON.stringify(objRefs[1]));
 
     console.log(table.get(deepCloneSecondObj));

答案 1 :(得分:0)

试试这个。你可能会得到你需要的东西。我做了一个小小的美化。

function trial() {
    var obj1 = {
            fund: 1,
            target: 2
        },
        obj2 = { 
            fund: 1,
            target: 2
        },
        obj = {},
        states = [
            obj1, obj2
        ],
        actions = [1,2,3,4],
        table = new Map(),
        cell
    ;
    for (var state of states) {
        for (var action of actions) {
            cell = {};
            cell.state = state;
            cell.action = action;
            table.set(cell, 0);   
        }
    }
    obj.state = states[1];
    obj.action = actions[1];
    return(obj);
    //console.log(table.get(obj));   
}
console.log(trial())