gpt4 book ai didi

Javascript Map 返回未定义,尽管(键,值)对已定义

转载 作者:行者123 更新时间:2023-12-03 02:14:01 24 4
gpt4 key购买 nike

我正在使用 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));
}

最佳答案

您需要原始对象引用来匹配表(Map())中的键,让我们保存每个新的单元格,它是每个对象引用来显示这一点。

即使你有对象的深度克隆,对于 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));

关于Javascript Map 返回未定义,尽管(键,值)对已定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49435697/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com