我有一個動態構建的JavaScript對象。我想在迭代期間替換可能已經存在的新屬性 - 基本上像Java HashSet一樣處理對象。單個Javascript對象屬性的多個值
爲什麼當你爲javascript對象添加一個動態屬性,然後用for for循環遍歷該對象時,你會得到該屬性的多個值或其他奇怪的行爲?
例子:
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' ]
怎樣才能覆蓋舊值與使用動態屬性一個新的?
你寫了'bam',而不是'bar',所以'bar'不會被修改。 – Blender
那些額外的特性是故意存在的,但Ehtan的答案突出顯示了真正的問題,即它按預期工作,但我拉動了小動作! – binarygiant