[英]Javascript Map returns undefined although (key, value) pair defined
我正在使用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
,每個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));
試試這個。 您可能會得到所需的東西。 我做了一個小小的美化。
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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.