strange behaviour with javascript map/object
I am using javascript map to store keys and values. Later on I check if specified key is present in map or not,开发者_开发百科 but it sometimes gives correct result but sometimes it don't. I tried to print the map using console.log(mapname)
, it shows all keys, but if I try to check if some specified key is present - sometimes it gives wrong answer.
Am using following code:
// 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');
What can be the possible problem? Can alphanumericstring/integers values can be used as keys?
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');
Be sure you're aware that the value stored with the key could be null, as the following code shows:
a = {
"mykey": null
}
for (x in a) {
if (a[x] == null) {
alert(x + " is null!");
}
} // produces a single alert: "mykey is null!"
I think you have to store keys in some temporary table or objects like session or cookies for future retrieve. you have dynamically store x position value in mymap[key] but every time it loads and overwrite your new values. you something doing wrong there..
精彩评论