CodeMash 2012的“ Wat”演讲基本上指出了Ruby和JavaScript的一些怪异之处。
我在http://jsfiddle.net/fe479/9/上对结果做了JSFiddle 。
下面列出了特定于JavaScript的行为(因为我不了解Ruby)。
我在JSFiddle中发现我的某些结果与视频中的结果不符,我不确定为什么。但是,我很想知道JavaScript在每种情况下如何处理幕后工作。
Empty Array + Empty Array
[] + []
result:
<Empty String>
+
当与JavaScript中的数组一起使用时,我对运算符非常好奇。这与视频结果匹配。
Empty Array + Object
[] + {}
result:
[Object]
This matches the video's result. What's going on here? Why is this an object. What does the +
operator do?
Object + Empty Array
{} + []
result
[Object]
This doesn't match the video. The video suggests that the result is 0, whereas I get [Object].
Object + Object
{} + {}
result:
[Object][Object]
This doesn't match the video either, and how does outputting a variable result in two objects? Maybe my JSFiddle is wrong.
Array(16).join("wat" - 1)
result:
NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
Doing wat + 1 results in wat1wat1wat1wat1
...
I suspect this is just straightforward behaviour that trying to subtract a number from a string results in NaN.
I second @Ventero’s solution. If you want to, you can go into more detail as to how
+
converts its operands.First step (§9.1): convert both operands to primitives (primitive values are
undefined
,null
, booleans, numbers, strings; all other values are objects, including arrays and functions). If an operand is already primitive, you are done. If not, it is an objectobj
and the following steps are performed:obj.valueOf()
. If it returns a primitive, you are done. Direct instances ofObject
and arrays return themselves, so you are not done yet.obj.toString()
。如果返回原语,则操作完成。{}
并且[]
都返回一个字符串,所以您完成了。TypeError
。对于日期,将交换步骤1和2。您可以观察到转换行为,如下所示:
交互(
Number()
首先转换为原始,然后转换为数字):第二步(第11.6.1节):如果一个操作数是一个字符串,则另一个操作数也将转换为字符串,并通过串联两个字符串来产生结果。否则,两个操作数都将转换为数字,并通过将它们相加来产生结果。
转换过程的详细说明:“ JavaScript中的{} + {}是什么?”