gpt4 book ai didi

javascript - Object(obj) === obj 是做什么的?

转载 作者:数据小太阳 更新时间:2023-10-29 05:22:54 26 4
gpt4 key购买 nike

不同于 obj != null;

我知道 obj != null 会检测到任何允许在其上具有属性的内容,因为 null 和 undefined 是仅有的两个不能具有属性的值。

这与

有何不同

对象(obj) === obj;

最佳答案

Object(obj) === obj 测试 obj 是对象还是原始类型,对于字符串等也失败。

console.log(Object('foo') === 'foo'); // false
console.log(Object(true) === true); // false
console.log(Object(null) === null); // false

var obj = {};
console.log(Object(obj) === obj); // true

它对于确定值是否可以并记住分配的属性很有用。

虽然 nullundefined 在尝试使用属性时完全错误,这就是 obj != null 仍然有用的原因,no primitive values are able to hold onto properties .

var pri = 'foo';
pri.foo = 'bar'; // no error, but still...
console.log(pri.foo); // undefined

var box = Object(pri);
box.foo = 'bar';
console.log(box.foo); // 'bar'

引用:

objnullundefined 时,Object(obj) returns a new Object() :

1) If value is null, undefined or not supplied, create and return a new Object object exactly as if the standard built-in Object constructor had been called with the same arguments (15.2.2.1).

并且,原始 bool 值、字符串和数字通过 ToObject() 装箱到它们的对象类型中,它们不等于它们的原始等价物:

2) Return ToObject(value).

console.log(typeof 'foo' === 'string');         // true
console.log(typeof Object('foo') === 'object'); // true

console.log('foo' instanceof String); // false
console.log(Object('foo') instanceof String); // true

关于javascript - Object(obj) === obj 是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24460874/

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