I get unexpected behavior when trying to load a hash using objects as keys; ie, when retrieving my data later the hash always refers to the last key used. I would expect this to be due to the behavior of closures, however, I thought that I have done what would be necessary to prevent this:
var hash = {};
var arry = [];
var list = [{val:"a"},{val:"b"},{val:"c"}];
var len = list.length;
dump("load : \n");
for (var i=0;i<len;i++) {
let pos = i;
let obj = list[pos];
hash[obj] = obj.val;
arry.push(obj);
dump(" "+obj.val+" "+hash[obj]+"\n");
}
dump("retrieve : \n");
for (var i=0;i<len;i++) {
let pos = i;
let obj = list[pos];
dump(" "+obj.val+" "+arry[pos].val+" "+hash[obj]+"\n");
}
output is:
load :
a a
b b
c c
retrieve :
a a c
b b c
c c c
I have purposely gone overboard in trying to prevent this by raising the scope of the iteration objects using let, still I am apparently missing something. I would like to understand the reason behind this, and how to prevent it using Javascript.