Javascript连接

Javascript连接,javascript,Javascript,我在一次javascript在线测试中发现了以下代码片段。我无法理解这种连接在JS中是如何工作的。有人能解释一下这是怎么回事吗 [] + [] = "" // output : "" [] + [] + "foo" // output : "foo" Javascript尝试以不同的方式应用+操作符,这是人们教给它的 因此,除非明确告知,否则它将调用数组的toString方法,这是告诉它添加两个数组时的最佳猜测 [] + [] = "" +[] + [] = "0" // If

我在一次javascript在线测试中发现了以下代码片段。我无法理解这种连接在JS中是如何工作的。有人能解释一下这是怎么回事吗

[] + [] = ""    // output : ""

[] + [] + "foo" // output : "foo"

Javascript尝试以不同的方式应用
+
操作符,这是人们教给它的

因此,除非明确告知,否则它将调用数组的toString方法,这是告诉它添加两个数组时的最佳猜测

[] + [] = ""

+[] + [] = "0"    // If you give a hint to cast one of the array to a Number

+[] + +[] = 0     // If you give a hint to cast both the arrays to Number

[]+[]+“foo”
只是

([] + []) + "foo" = "" + "foo" = "foo"

当您说
[]
+
[]
时,JavaScript会尽力将操作数转换为数字

根据,

因此,首先,尝试使用将它们转换为基本值。由于数组是对象,JavaScript尝试检索默认值并将其用作基本值

返回对象的默认值。通过调用对象的[[DefaultValue]]内部方法并传递可选提示PreferredType,可以检索对象的默认值。[[DefaultValue]]内部方法的行为由本规范为8.12.8中的所有本机ECMAScript对象定义

当没有任何提示调用时,默认情况下,它将被视为数字。

当在没有提示的情况下调用O的[[DefaultValue]]内部方法时,它的行为就像提示是数字一样,除非O是日期对象(参见15.9.6),在这种情况下,它的行为就像提示是字符串一样

默认值是这样检索的

因此,它尝试获取对象的
值,并尝试执行该值,返回
[]
,而该值不是原始值。这个定义是这样的

第8条中定义的未定义、Null、Boolean、Number或String类型之一的成员

由于它们都不能转换为基元值,因此会使用
toString
将它们转换为字符串。因为它们是空数组,所以字符串值也是空字符串

这就是为什么

console.log([] + [] === "");
# true

您还可以解释一下+[]gives 0是如何看待它的
-[]
gives
-0
。因此这里的
+
表示一个数字的符号,暗示JS解释器将下面的项目
[]
转换为一个数字
1. Let valueOf be the result of calling the [[Get]] internal method of object O with argument "valueOf".
2. If IsCallable(valueOf) is true then,
    a. Let val be the result of calling the [[Call]] internal method of valueOf, with O as the this value and an empty argument list.
    b. If val is a primitive value, return val.
3. Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".
4. If IsCallable(toString) is true then,
    a. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.
    b. If str is a primitive value, return str.
5. Throw a TypeError exception.
console.log([] + [] === "");
# true