hasOwnProperty("foo") 始终 returns true 即使我将 foo 分配给 undefined - 为什么?

hasOwnProperty("foo") always returns true even if I assigned foo to undefined - why?

如果条件为真,我想将对象的 属性 设置为某个值,否则什么也不做。

并且我尝试使用 ? 运算符

obj.prop = (...)?sth:null;

obj.prop = (...)?sth:undefined;

但事实证明,他们中没有一个能做到我想要的。

鉴于条件为假,当我调用 obj.hasOwnProperty(prop) 时,它总是给我真。

有办法吗?

我知道我可以使用 if 语法来做到这一点,但我只想知道我是否可以使用 ? 运算符来做同样的事情。

当您像这样分配 属性 时:

var obj = {
    a : undefined // or any other value
};

这是根据 ECMAScript 规范发生的:

11.1.5 Object Initialiser

[...]

The production PropertyNameAndValueList : PropertyAssignment is evaluated as follows:

  1. Let obj be the result of creating a new object as if by the expression new Object() where Object is the standard built-in constructor with that name.
  2. Let propId be the result of evaluating PropertyAssignment.
  3. Call the [[DefineOwnProperty]] internal method of obj with arguments propId.name, propId.descriptor, and false.
  4. Return obj.

当您像这样分配 属性 时:

obj.a = undefined;

这是根据 ECMAScript 规范发生的:

8.12.5 [[Put]] ( P, V, Throw )

[...]

  1. Else, create a named data property named P on object O as follows a. Let newDesc be the Property Descriptor {[[Value]]: V, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true}. b. Call the [[DefineOwnProperty]] internal method of O passing P, newDesc, and Throw as arguments.

在任何一种情况下,由于 undefinednull 是合法值,这将只用该值定义 属性。

最后,hasOwnProperty() 只会检查是否创建了 属性 描述符,值无关紧要:

15.2.4.5 Object.prototype.hasOwnProperty (V)

[...]

  1. Let desc be the result of calling the [[GetOwnProperty]] internal method of O passing P as the argument.
  2. If desc is undefined, return false.
  3. Return true.

但是,根据 ECMAScript 规范,属性 设置为 undefined 和未设置 属性,如果您将 return undefined访问它们:

8.12.3 [[Get]] (P)

[...]

  1. If desc is undefined, return undefined.
  2. If IsDataDescriptor(desc) is true, return desc.[[Value]].
  3. Otherwise, IsAccessorDescriptor(desc) must be true so, let getter be desc.[[Get]].
  4. If getter is undefined, return undefined.
  5. Return the result calling the [[Call]] internal method of getter providing O as the this value and providing no arguments.

证明:

var obj = {
  a : undefined
}

console.log(typeof obj.a); // undefined
console.log(typeof obj.b); // undefined
obj.hasOwnProperty('a') // true
obj.hasOwnProperty('b') // false

只有 delete 会删除 属性。

var obj = {
  a : null,
  b : undefined
}

obj.hasOwnProperty('a') // true
obj.hasOwnProperty('b') // true

delete obj.a;
delete obj.b;

obj.hasOwnProperty('a') // false
obj.hasOwnProperty('b') // false

阅读 delete 上的 ECMAScript 规范留给 reader。

假设您的条件的结果足够虚假,这样的事情应该有效。 All falsey values in JavaScript

var obj = {

  a: true,
  b: false,

}

obj.prop1 = obj.a ? true : false;
obj.prop2 = obj.b ? true : false;

console.log(obj);