删除多个对象属性? [英] Delete multiple object properties?
问题描述
我创建了一个具有多个属性的对象-
I create an object with multiple properties -
var objOpts = {
option1: 'Option1',
option2: 'Option2',
option2: 'Option3'
};
然后我在稍后添加更多属性-
I then add some more properties later on -
objOpts.option4 = 'Option4'
objOpts.option5 = 'Option5'
然后我完成了后两个创建的属性('Option4'和'Option5'),并且我想清除/删除这两个属性.
I'm then done with the two latter created properties ('Option4' & 'Option5') and I want to clear/delete both.
目前,我会这样做-
delete objOpts.option4
delete objOpts.option5
还有另一种方法可以做到这一点吗?想象一下,我又添加了5个属性,并且需要清除/删除它们,而这将是五行几乎相同的删除"代码
Is there another way to go about doing this? Imagine I'd added 5 more properties and needed to clear/delete them all that'd be five lines of almost identical 'delete' code
推荐答案
我确定您正在尝试向对象添加自定义属性.
I'm sure you are trying to add custom properties to an object.
我建议的一种更简单的方法是创建一个子属性:
A simpler way I would suggest is by creating a sub property:
objOpts.custom.option4 = 'Option4'
objOpts.custom.option5 = 'Option5'
这样,您可以删除objOpts.custom
并完成它.请注意,在此步骤之后,您将必须重新创建 objOpts.custom = {}
.
this way you could delete objOpts.custom
and get done with it. Note that after this step you would have to recreate objOpts.custom = {}
.
此外,由于您的公共财产很容易与私人财产区分开来,因此这种方式也更接近OOP.
Moreover this way would also feel closer to OOP, since your public properties would easily be distinguishable from private ones.
如果您开始删除JavaScript中的对象,那么我想指向一篇有关该主题的出色文章:
If you are beginning with deleting objects in JavaScript, I'd like to point to to an excellently written article on the topic: http://perfectionkills.com/understanding-delete/
您可以尝试使用元属性,以防止属性被删除等(为您的案例创建更好的编码流程)
You could play around with the meta properties which allow you to protect properties from being deleted etc. (to create an even better coding flow for your case)
我想添加该内容,而不是删除并重新创建该属性,您只需说出 objOpts.custom = {}
即可释放 option4
和 option5
从内存中(最终通过垃圾回收).
I'd like to add that instead of deleting and recreating the property, you could simply say objOpts.custom = {}
which would release the option4
and option5
from memory (eventually, via Garbage Collection).
这篇关于删除多个对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!