How [1,2] + [4,5,6][1] = 1,25 in JavaScript [duplicate]

风流意气都作罢 提交于 2019-12-03 16:16:49

问题


I got this question from Interview,

[1,2] + [4,5,6][1]

JavaScript giving answer 1,25.

How it's happening? Please explain clearly.


回答1:


Lets start with the last part and write it more verbose

var arr   = [4,5,6];
var value = arr[1];

Is the same as

[4,5,6][1]

and as arrays are zero based, that gives 5, so we really have

[1,2] + 5;

The first part is equal to

[1,2].toString(),

and that returns the string "1,2" because the array is converted to a string when trying to use it in an expression like that, as arrays can't be added to numbers, and then we have

"1,2" + 5

Concatenating strings with numbers gives strings, and adding the strings together we get

"1,25"



回答2:


It breaks down like this:

Starting with:

[1,2] + [4,5,6][1]

First, each side gets evaluated, and since the right-hand side is an array initializer and lookup, it comes out to 5:

[1,2] + 5

Now the + operator starts its work. It isn't defined for arrays, the first thing it does is try to convert its operands into either strings or numbers. In the case of an array, it'll be a string as though from Array#toString, which does Array#join, giving us:

"1,2" + 5

When you use + where either side is a string, the result is string concatenation.




回答3:


First, [4,5,6][1] evaluates to the number 5

Then, the + operator is being applied to a first argument which is an Array and not a Number, so javascript assumes you're doing a string concatenation, not addition. Your array [1,2] becomes a string, which is "1,2". You can see this yourself with [1,2].toString().

The number 5 is now being appended to a string, so it to gets converted to a string, and appended together to get "1,25".



来源:https://stackoverflow.com/questions/29867933/how-1-2-4-5-61-1-25-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!