我正在使用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));
}
您需要原始对象引用来匹配table(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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句