我有一个在循环中动态构建的 javascript 对象。我想在迭代期间用较新的属性替换可能已经存在的属性 - 基本上将对象视为 Java HashSet。
为什么当您向 javascript 对象添加动态属性,然后使用 for in 循环遍历该对象时,您会获得该属性的多个值或其他奇怪的行为?
例子:
var foo = {};
foo['bar'] = 'hello';
foo['bar'] = 'hola';
foo['bar'] = 'aloha';
foo['baz'] = 'some other thing';
var arr = [];
for(var prop in foo) { arr.push(foo[prop]) };
//2 entries (what I'd expect)
foo['bam'] = 'other other thing';
for(var prop in foo) { arr.push(foo[prop]) };
//5 entries (why?) the [bar] property should be overwritten right?
console.log(arr);
[ 'aloha',
'some other thing',
'aloha',
'some other thing',
'other other thing' ]
如何使用动态属性用新值覆盖旧值?