JavaScript null and plus (+) operatior

后端 未结 2 1308
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 08:22

I am trying to understand the core of JavaScript. I know it doesnt have much implementation value. If you dont want to answer, just leave it. However, I will appreciate if y

相关标签:
2条回答
  • 2020-12-10 08:44

    Conclusions derived from analysing results

    true coerces to 1 (and false to 0).

    null coerces to 0.

    undefined coerces to NaN.

    Arrays behave as:

    • under unary + (+[]):
      • their first element if length is 1
      • 0 if they're empty
      • NaN if there's more than 1 element
    • under binary + (1+[]):
      • coerces both operators to strings and joins them

    All operations on NaN return NaN

    0 讨论(0)
  • 2020-12-10 08:56

    This is covered in 11.6.1 The Addition operator ( + ) - feel free to read it and follow the rules.

    The first five cases can be explained by looking at ToNumber:

    Value       ToNumber(Value)
    ---------   ---------------
    null        0
    undefined   NaN
    NaN         NaN
    1           1
    true        1
    

    And 0 + 0 == 0 (and 1 + 0 == 1), while x + NaN or NaN + x evaluates to NaN. Since every value above is also a primitive, ToPrimitive(x) evaluates to x (where x is not a string) and the "string concatenation clause" was not invoked.

    The final case is different in that it results from the ToPrimitive (which ends up calling Array.prototype.toString) on the array which results in a string value. Thus it ends up applying ToString, not ToNumber, and follows as such:

       true + [null]
    => true + ""          // after ToPrimitive([null]) => ""
    => "true" + ""        // after ToString(true) => "true"
    => "true"             // via String Concatenation
    
    0 讨论(0)
提交回复
热议问题