如何从对象中删除属性? [英] How to remove a property from an object?
问题描述
目前在复选框上设置了一个事件
, event.target
给了我单击复选框的status(checked = true / false)
。
我正在维护一个对象,该对象保留所有选中复选框的轨道
I am maintaining an object which keeps the track on all the selected checkboxes
var selectedMap = {};
if(event.target == true){
var key = event.target.id;
var val = event.target.name;
selectedMap[key] = val;
}
我希望从地图中删除未选中的元素
and I want to remove the element from the map which is unselected
else if(event.target == false){
selectedMap.remove(event.target.id);
}
当我运行它时,它给我错误 Firebug
: selectedMap.remove不是函数
when I run this it gives me error in Firebug
: selectedMap.remove is not a function
所以我的问题是 如何在取消选中复选框时删除元素?
So my question is How can I remove the element when the checkbox is unselected ?
推荐答案
使用删除
:
delete selectedMap[event.target.id];
但是,您设置的值不正确。这是正确的方法:
You're setting the value incorrectly, though. Here's the correct way:
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;
}
获取事件目标的东西,更容易设想这个简单字符串:
Getting the event target stuff out of the way, it's easier to envision this with simple strings:
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]属性,并且很快就会非常奇怪。)
When using a plain object like this, I always use a prefix on my keys to avoid issues. (For instance, what would happen if your target element's ID was "toString"? The object already has an [inherited] property called "toString" and things would get Very Weird Very Quickly.)
所以对我来说,我这样做:
So for me, I do this:
if(event.target == true){
selectedMap["prefix" + event.target.id] = event.target.name;
}
......当然还有:
...and of course:
delete selectedMap["prefix" + event.target.id];
这篇关于如何从对象中删除属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!