我使用javascript地图来存储键和值。稍后我会检查地图中是否存在指定的键,但它有时会给出正确的结果,但有时却没有。我尝试使用console.log(mapname)
打印地图,它显示所有键,但如果我尝试检查是否存在某个指定的键 - 有时它会给出错误的答案。
使用以下代码:
// following code is called n times in loop with different/same vales of x
myMap : new Object();
var key = x ; // populated dynamically actually
myMap[key] = "dummyval";
if(myIdMap[document.getElementById("abc").value.trim()] != null)
alert('present');
else
alert('not present');
可能出现什么问题? alphanumericstring / integers值可以用作键吗?
答案 0 :(得分:0)
var myMap = {};
// ...
//simulating your inner loop; is this close enough?
//Note: A MacGuffin is a plot device to move the story forward.
// Like a time machine, or a space ship.
for (var key in macGuffin) {
myMap[key] = macGuffin.processItem(key);
}
// ...
var myKey = document.getElementById("abc").value.trim();
//Note the use of !==; false == null == 0 == '', but null only === null
if (myMap[myKey]!==null)
//Better? (typeof myMap[myKey] != 'undefined')
console.log('present');
else
console.log('not present');
答案 1 :(得分:0)
请确保您知道使用密钥存储的值可能为null,如下面的代码所示:
a = {
"mykey": null
}
for (x in a) {
if (a[x] == null) {
alert(x + " is null!");
}
} // produces a single alert: "mykey is null!"
答案 2 :(得分:-1)
我认为您必须将密钥存储在某些临时表或会话或cookie等对象中以供将来检索。 你已经在mymap [key]中动态存储x位置值,但每次加载并覆盖你的新值。你那里做错了..