gpt4 book ai didi

javascript - 为什么新对象 ("foo") 返回 "[object Object]"

转载 作者:行者123 更新时间:2023-11-30 13:34:52 25 4
gpt4 key购买 nike

Array.prototype.sort.call("foo"); // "[object Object]"
Array.prototype.sort.call(true); // true
Array.prototype.sort.call(1); // 1
Array.prototype.sort.call([1]); // [1]
Array.prototype.sort.call({}); // {}
Array.prototype.sort.call(function() {}); // function() {}

为什么对字符串调用数组方法的行为不同?我认为这是因为 String 也有 .length[] 元素访问器。

谁能解释一下当您在错误的类型上调用 native 方法时到底发生了什么?

[编辑]

糟糕,我解决了。

new Object("foo"); // "[object Object]"

其余的都一样。

让我们谈谈 ES5 规范:

15.2.1.1 Object ( [ value ] ) When the Object function is called with no arguments or with one argument value, the following steps are taken:

  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).

  2. Return ToObject(value)

ToObject 是:

9.9 ToObject The abstract operation ToObject converts its argument to a value of type Object according to Table 14:

Table 14 — ToObject Argument Type Result

Undefined Throw a TypeError exception.

Null Throw a TypeError exception.

Boolean Create a new Boolean object whose [[PrimitiveValue]] internal property is set to the value of the argument. See 15.6 for a description of Boolean objects.

Number Create a new Number object whose [[PrimitiveValue]] internal property is set to the value of the argument. See 15.7 for a description of Number objects.

String Create a new String object whose [[PrimitiveValue]] internal property is set to the value of the argument. See 15.5 for a description of String objects. Object The result is the input argument (no conversion).

[赏金]

现在为什么 String[[PrimitiveValue]] 等于 [object Object]"

最佳答案

这里的“问题”是该类型的构造函数被调用(Number、String、Array、Boolean...),它们的行为与它们的“原始”对应物有点不同——它们返回一个包含原始值的对象。

此 [[PrimitiveValue]] 或先前规范中的 [[value]] 是一个内部属性,您可以通过 .valueOf() 访问它。

'foo' // is a string
String('foo') // is a string
new String('foo') // is a String object with [[value]] set to 'foo'

1 // is a number
Number(1) // is a number
new Number(1) // is a Number object with [[value]] set to 1

Object('foo') == (new String('foo'))
Object(1) == (new Number(1))

出于某种原因,webkit 检查器似乎没有意识到这些对象的原始值。因此,Object('foo') 将打印'[object Object]',但是如果您调用 Object('foo').toString() 或任何隐含的方法调用 toString 或 valueOf,如 alert(Object('foo')),您将获得预期值“foo”。

也是这个原因:

var x = new Boolean(false);
// any object evaluates to true...
!!x // == true
Boolean(x) // == true

Javascript 有相当多的怪异之处。还要考虑到 javascript 引擎中有很多怪癖,对规范的遵守程度各不相同。

关于javascript - 为什么新对象 ("foo") 返回 "[object Object]",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5277659/

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