Why adding an array to a number returns a string?

var array = [1,2,4];

array+1  //gives '1,2,41'.

Can anyone explain this behavior?

+6
source share
5 answers

Can anyone explain this behavior?

This answer attempts to explain this behavior in terms of specification.

According to spec , during time evaluation, +both expressions (left and right) are converted to their primitive values.

  1. Let lprim be ToPrimitive (lval).
  2. Let rprim be ToPrimitive (rval).

toPrimitive tries to pass hint:number(after the call during arithmetic evaluation) to OrdinaryToPrimitive

  1. "", . methodNames "toString", "valueOf" ".
  2. Else,
    . methodNames " "valueOf", "toString" ".//

, 4a) , .

[1,2,4] + 1 = > [1,2,4].toString() + "1" = > "1,2,4" + "1" = > () "1,2,41"

+3

- , .

+4

+ javascipt (var array), , - .

[1,2,4] 1,2,4. , 1,2,4, 1, 1,2,41

+2

? [2,3,5]?

, 1 ( ). , 1 ?

JS , . , "" 2 ( ), .

, +1 . :

for (var i=array .length; i--;) {
    array [i]++;
}

array = array.map(function(e) {return '#' + e});

ES6

array = array.map(i => i + 1);
0

, .

Both an array and a number can be converted to a string, this is called coercion .

If you want to add 1to an array, you can do this:

var array = [1,2,4];
array.push(1);
0
source

All Articles