在 JavaScript 中,为什么 +[1.5] 被认为是数字?
In JavaScript, why is +[1.5] considered numeric?
我已经 JavaScript 做了 很长时间 了,但刚刚注意到一些我以前从未见过的东西。考虑:
> +[1.5]
1.5
为什么会这样?这是将数组解释为数值的特殊规则还是规范炼金术的意外?
另请注意:
> +[1,0]
NaN
当然,这对我来说很有意义,但我本以为 +[1]
也是 NaN,因为它不是数字。还是以某种方式归类为数字?
还有这些情况,让我相信我们正在穿越类型强制虫洞(数组 ==> 字符串,字符串 ==> 数字):
> [2] + [4]
"24"
> + [2] + [4]
"24"
> (+[2]) + (+[4])
6
> +[2] + [4,5]
"24,5"
> // which, incidentally, looks like a european-formatted number, but I see
> // that that's just an accident (still another possibility for confusion)
这是故意的吗?
一元 +
运算符在内部使用 ToNumber 抽象运算。
所以一元运算符在应用于对象时首先应用toString()
(抽象操作ToPrimitive)然后应用ToNumber抽象操作,所以基本上 +
当应用于单个数字数组时,它会将其转换为数字本身。
如果应用于 [4,5]
,则 toString 将 return 4,5
当应用 ToNumber 抽象操作时反过来 returns NaN。
// Trying to concatenate two string as [] coerce to strings = 24
[2] + [4]
// Converting 2 and 4 to number and then adding = 6
(+[2]) + (+[4])
// Converting 2 to number and 4,5 will be coerced to string = 24,5
+[2] + [4,5]
在将一元 +
应用于数组之前,它使用 toString
转换为字符串,然后尝试将其转换为数字。
所以
+[1.5]
充当
+([1.5].toString())
因此
+[1,0]
将 [1,0](由两个元素组成的数组)转换为字符串 1,5
,然后尝试将其转换为数字
+[1,0] => +"1,0" => NaN
在这个例子中:
+[2] + [4,5] => +"2" + "4,5" => 2 + "4,5" => "24,5"
我已经 JavaScript 做了 很长时间 了,但刚刚注意到一些我以前从未见过的东西。考虑:
> +[1.5]
1.5
为什么会这样?这是将数组解释为数值的特殊规则还是规范炼金术的意外?
另请注意:
> +[1,0]
NaN
当然,这对我来说很有意义,但我本以为 +[1]
也是 NaN,因为它不是数字。还是以某种方式归类为数字?
还有这些情况,让我相信我们正在穿越类型强制虫洞(数组 ==> 字符串,字符串 ==> 数字):
> [2] + [4]
"24"
> + [2] + [4]
"24"
> (+[2]) + (+[4])
6
> +[2] + [4,5]
"24,5"
> // which, incidentally, looks like a european-formatted number, but I see
> // that that's just an accident (still another possibility for confusion)
这是故意的吗?
一元 +
运算符在内部使用 ToNumber 抽象运算。
所以一元运算符在应用于对象时首先应用toString()
(抽象操作ToPrimitive)然后应用ToNumber抽象操作,所以基本上 +
当应用于单个数字数组时,它会将其转换为数字本身。
如果应用于 [4,5]
,则 toString 将 return 4,5
当应用 ToNumber 抽象操作时反过来 returns NaN。
// Trying to concatenate two string as [] coerce to strings = 24
[2] + [4]
// Converting 2 and 4 to number and then adding = 6
(+[2]) + (+[4])
// Converting 2 to number and 4,5 will be coerced to string = 24,5
+[2] + [4,5]
在将一元 +
应用于数组之前,它使用 toString
转换为字符串,然后尝试将其转换为数字。
所以
+[1.5]
充当
+([1.5].toString())
因此
+[1,0]
将 [1,0](由两个元素组成的数组)转换为字符串 1,5
,然后尝试将其转换为数字
+[1,0] => +"1,0" => NaN
在这个例子中:
+[2] + [4,5] => +"2" + "4,5" => 2 + "4,5" => "24,5"