删除a.x vs a.x = undefined [英] delete a.x vs a.x = undefined
问题描述
执行其中任何一项是否有任何实质性差异?
Is there any substantial difference in doing either of these?
delete a.x;
vs
a.x = undefined;
其中
a = {
x: 'boo'
};
可以说它们是等价的吗?
could it be said that they are equivalent?
(我没有考虑像V8喜欢不使用删除
更好)
(I'm not taking into account stuff like "V8 likes not using delete
better")
推荐答案
<他们并不等同。主要区别在于设置
They are not equivalent. The main difference is that setting
a.x = undefined
意味着 a.hasOwnProperty(x)
仍然会返回true,因此它仍将显示在 for
循环, Object.keys()
means that a.hasOwnProperty("x")
will still return true, and therefore, it will still show up in a for in
loop, and in Object.keys()
delete a.x
表示 a.hasOwnProperty(x)
将返回false
means that a.hasOwnProperty("x")
will return false
它们相同的方式是你无法判断一个属性通过测试存在
The way that they are the same is that you can't tell if a property exists by testing
if (a.x === undefined)
如果你想确定某个房产是否存在,你不应该这样做,你应该总是使用
Which you shouldn't do if you are trying to determine if a property exists, you should always use
// If you want inherited properties
if ('x' in a)
// If you don't want inherited properties
if (a.hasOwnProperty('x'))
跟随原型链(由zzzzBov )调用 delete
将允许它上传原型链,而将值设置为undefined将不会在链式原型中查找属性 http:/ /jsfiddle.net/NEEw4/1/
Following the prototype chain (mentioned by zzzzBov) Calling delete
will allow it to go up the prototype chain, whereas setting the value to undefined will not look for the property in the chained prototypes http://jsfiddle.net/NEEw4/1/
var obj = {x: "fromPrototype"};
var extended = Object.create(obj);
extended.x = "overriding";
console.log(extended.x); // overriding
extended.x = undefined;
console.log(extended.x); // undefined
delete extended.x;
console.log(extended.x); // fromPrototype
删除继承的属性如果您要删除的属性继承,删除
不会影响它。也就是说, delete
只删除对象本身的属性,而不是继承的属性。
Deleting Inherited Properties If the property you are trying to delete is inherited, delete
will not affect it. That is, delete
only deletes properties from the object itself, not inherited properties.
var obj = {x: "fromPrototype"};
var extended = Object.create(obj);
delete extended.x;
console.log(extended.x); // Still fromPrototype
因此,如果您需要确保对象的值未定义,<$当继承该属性时,c $ c> delete 将无效,在这种情况下,您必须将其设置(覆盖)为 undefined
。除非检查它的地方将使用 hasOwnProperty
,但是假设在任何地方检查它将使用 hasOwnProperty
Therefore, if you need to make sure an object's value will be undefined, delete
will not work when the property is inherited, you will have to set (override) it to undefined
in that case. Unless the place that is checking for it will use hasOwnProperty
, but it likely wouldn't be safe to assume that everywhere that checks it will use hasOwnProperty
这篇关于删除a.x vs a.x = undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!