删除 a.x 与 a.x = 未定义不。

2022-08-30 01:57:32

做这些有什么实质性的区别吗?

delete a.x;

a.x = undefined;

哪里

a = {
    x: 'boo'
};

可以说它们是等价的吗?

(我没有考虑到诸如“V8喜欢不更好地使用删除之类的东西)


答案 1

它们不是等效的。主要区别在于设置

a.x = undefined

意味着仍将返回 true,因此,它仍将显示在循环中,并在 .而a.hasOwnProperty("x")for inObject.keys()

delete a.x

表示将返回 falsea.hasOwnProperty("x")

您无法通过测试来判断属性是否存在

if (a.x === undefined)

如果尝试确定某个属性是否存在,则应始终使用

// If you want inherited properties
if ('x' in a)

// If you don't want inherited properties
if (a.hasOwnProperty('x'))

遵循原型链(由zzzzBov提到)调用将允许它沿着原型链向上移动,而将值设置为未定义将不会在链接的原型中查找属性delete

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

删除继承的属性如果您尝试删除的属性是继承的,则不会影响它。也就是说,仅从对象本身中删除属性,而不删除继承的属性。deletedelete

var obj = {x: "fromPrototype"};
var extended = Object.create(obj);
delete extended.x;
console.log(extended.x); // Still fromPrototype

因此,如果您需要确保对象的值未定义,并且在继承属性时不起作用,则必须在这种情况下将其设置(重写)为。除非正在检查它的地方将使用,但假设检查它的所有地方都会使用,它可能不会安全。deleteundefinedhasOwnPropertyhasOwnProperty


答案 2

解释一下这个问题:

是等价的吗?delete a.xa.x = undefined

不。

前者从变量中删除键,后者将键设置为值 。这在迭代对象的属性和使用对象时会有所不同。undefinedhasOwnProperty

a = {
    x: true
};
a.x = undefined;
a.hasOwnProperty('x'); //true
delete a.x;
a.hasOwnProperty('x'); //false

此外,当涉及原型链时,这将产生重大影响。

function Foo() {
    this.x = 'instance';
}
Foo.prototype = {
    x: 'prototype'
};
a = new Foo();
console.log(a.x); //'instance'

a.x = undefined;
console.log(a.x); //undefined

delete a.x;
console.log(a.x); //'prototype'