gpt4 book ai didi

javascript - 将属性设置为 null

转载 作者:行者123 更新时间:2023-11-29 16:48:34 25 4
gpt4 key购买 nike

拥有代码:

foo = {};
foo.bar = 78;
foo.bar.baz = null;

针对 null 测试 foo.bar.baz:

if( foo.bar.baz === null )
console.log("foo.bar.baz is null");
else
console.log("foo.bar.baz is NOT null");

结果为“foo.bar.baz 不为空”。为什么它不是 null 因为我明确地设置了它?

最佳答案

因为基元没有属性,而 foo.bar 中的值是原始的。

当您访问(获取或设置)基元的属性时,JavaScript 引擎会为该基元创建一个对象,设置或检索属性值(如果有),然后丢弃该对象。 (这就是 (42).toString() 起作用的原因;原语被提升为由 Number.prototype 支持的对象,从该对象中检索 toString 并使用 this 调用该对象,然后该对象被丢弃。)

因此,尽管在您的 foo.bar.baz = null 中创建了一个对象声明,及其 baz属性设置为 null ,该对象从未存储在任何地方(当然不在 foo.bar 中),因此它被丢弃了。稍后当你做 if (foo.bar.baz === null) , 一个没有属性的对象被创建并且你得到undefined为其baz属性(property)(因为它没有)。 (当然,JavaScript 引擎可以优化这个过程以避免不必要的对象创建。)

我们可以在 Number.prototype 上创建一个函数返回创建的对象,以证明每次访问基元上的属性时确实会创建对象:

// Add a `nifty` method to numbers
Object.defineProperty(
Number.prototype,
"nifty",
{
value: function() {
console.log("Number#nifty called");
return this;
}
}
);

var n = 42; // A primitive number
console.log(typeof n); // "number"
var obj1 = n.nifty(); // Creates an object, which we keep
console.log(typeof obj1); // "object"
var obj2 = n.nifty(); // Do it again, and a new object is created
console.log(obj1 === obj2); // false, they're not the same object

如果你想设置一个数字的属性并保留它们,你可以通过显式创建一个 Number 来实现。对象:

var n = new Number(42);
n.baz = null;
console.log(n.baz === null); // true

很少有人想这样做,但这是可能的。请注意,正如我们之前展示的那样,两个 Number具有相同原始值的对象不是==对彼此:

var n1 = new Number(42);
var n2 = new Number(42);
console.log(n1 == n2); // false
console.log(n1 === n2); // false

> , < , >= , 和 <=会将数字强制返回原始值并使用原始值,但是 =====不会的。

关于javascript - 将属性设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38290441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com