[removed] array plus number [duplicate]

2020-04-16 18:44发布

Some operations in javascript returns unexpected results. One is extremely strange:

[] + 1 = "1"

Can anybody explain why it works like that?

标签: javascript
3条回答
够拽才男人
2楼-- · 2020-04-16 19:16

Javascript's rules for addition between differeent types are as follows:

Given the following addition.

value1 + value2

To evaluate this expression, the following steps are taken (§11.6.1): Convert both operands to primitives (mathematical notation, not JavaScript):

prim1 := ToPrimitive(value1)
prim2 := ToPrimitive(value2)

PreferredType is omitted and thus Number for non-dates, String for dates. If either prim1 or prim2 is a string then convert both to strings and return the concatenation of the results.

Otherwise, convert both prim1 and prim2 to numbers and return the sum of the results.

Source

In this case the array gets converted to an empty string, and then the + performs string concatenation

查看更多
beautiful°
3楼-- · 2020-04-16 19:19

[] are converted to an empty string due to + operator. so "" + 1 => "1" (number converted to string too)

查看更多
SAY GOODBYE
4楼-- · 2020-04-16 19:25

ECMAScript 11.6.1 defines addition. Steps 5 and 6 of addition call ToPrimitive (9.1) for each operand and operate on those results:

  • For an array (or any object), ToPrimative calls the toString method of the object. The result of calling toString on an empty array is the empty string (per the behavior described in 15.4.4.2.

  • For a number, ToPrimitive returns the number (since numbers are already primitive).

We're left adding the empty string and the number 1. When either operand in addition is a string, the addition acts as a concatenation operation (per addition's step 7), so we end up with "" + "1" = "1".

查看更多
登录 后发表回答