使用delete
:
delete selectedMap[event.target.id];
你沒有正確地設定值,雖然。下面是正確的方法:
if(event.target == true){
var key = event.target.id; // <== No quotes
var val = event.target.name; // <== Here either
selectedMap[key] = val;
}
事實上,你可以:
if(event.target == true){
selectedMap[event.target.id] = event.target.name;
}
獲取事件目標東西出來的方式,它更容易與簡單的字符串設想這樣的:
var obj = {};
obj.foo = "value of foo";
alert(obj.foo); // alerts "value of foo" without the quotes
alert(obj["foo"]); // ALSO alerts "value of foo" without the quotes, dotted notation with a literal and bracketed notation with a string are equivalent
delete obj.foo; // Deletes the `foo` property from the object entirely
delete obj["foo"]; // Also deletes the `foo` property from the object entirely
var x = "foo";
delete obj[x]; // ALSO deeltes the `foo` property
當使用這樣的普通對象時,我總是在我的鍵上使用前綴以避免問題。 (例如,如果你的目標元素的ID是「toString」會發生什麼?該對象已經有一個名爲「toString」的[inherited]屬性,並且事情很快會變得非常奇怪)。這樣的:
if(event.target == true){
selectedMap["prefix" + event.target.id] = event.target.name;
}
...當然:
delete selectedMap["prefix" + event.target.id];
可能重複(http://stackoverflow.com/questions/208105/how-從一個JavaScript對象中刪除屬性) – Thomas 2012-05-28 19:42:16