我想在 javascript 中将键保存为对象,所以我尝试使用 Map 集合作为
let tempEntry = {y:y,x:x}
let exist = map1.has(tempEntry);
if(exist){
map1.set(tempEntry,true)
}else{
map1.set(tempEntry,false)
}
但它找不到 key 并且总是返回 exist as false.. 我有一个列表,我也使用 x 和 y 并将其放入 tempEntry 变量中。
我想做的是对象列表 键:{y:y,x:x},值:真/假
还有其他方法吗?
最佳答案
Map#has
检查相同的对象引用。
如果您有另一个具有相同键/值的对象,您将无法获得原始对象。
var x = 4,
y = 4,
tempEntry = { y, x },
map1 = new Map;
map1.set(tempEntry, map1.has(tempEntry));
console.log([...map1]);
map1.set(tempEntry, map1.has(tempEntry)); // sets true
console.log([...map1]);
tempEntry = { y, x };
map1.set(tempEntry, map1.has(tempEntry)); // new object
console.log([...map1]);
.as-console-wrapper { max-height: 100% !important; top: 0; }
如果键的顺序相同,可能的解决方案可能是对象的序列化字符串。
var x = 4,
y = 4,
tempEntry = JSON.stringify({ y, x }),
map1 = new Map;
map1.set(tempEntry, map1.has(tempEntry));
console.log([...map1]);
tempEntry = JSON.stringify({ y, x });
map1.set(tempEntry, map1.has(tempEntry)); // same object
console.log([...map1]);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 将唯一键保存为任何集合中javascript中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49340487/