在CodeMash 2012的“ Wat”演讲中提到的这些怪异JavaScript行为的解释是什么?

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.

Jim老丝达蒙2020/03/11 11:26:56

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 object obj and the following steps are performed:

  1. Call obj.valueOf(). If it returns a primitive, you are done. Direct instances of Object and arrays return themselves, so you are not done yet.
  2. 致电obj.toString()如果返回原语,则操作完成。{}并且[]都返回一个字符串,所以您完成了。
  3. 否则,抛出一个TypeError

对于日期,将交换步骤1和2。您可以观察到转换行为,如下所示:

var obj = {
    valueOf: function () {
        console.log("valueOf");
        return {}; // not a primitive
    },
    toString: function () {
        console.log("toString");
        return {}; // not a primitive
    }
}

交互(Number()首先转换为原始,然后转换为数字):

> Number(obj)
valueOf
toString
TypeError: Cannot convert object to primitive value

第二步(第11.6.1节):如果一个操作数是一个字符串,则另一个操作数也将转换为字符串,并通过串联两个字符串来产生结果。否则,两个操作数都将转换为数字,并通过将它们相加来产生结果。

转换过程的详细说明:“ JavaScript中的{} + {}是什么?