Why is [1,2] + [3,4] = “1,23,4” in JavaScript?

前端 未结 13 1498
小蘑菇
小蘑菇 2020-11-22 16:56

I wanted to add the elements of an array into another, so I tried this:

[1,2] + [3,4]

It responded with:

\"1,23,4\"
         


        
相关标签:
13条回答
  • 2020-11-22 17:23

    It's converting the individual arrays to strings, then combining the strings.

    0 讨论(0)
  • 2020-11-22 17:24

    Another result using just a simple "+" sign will be:

    [1,2]+','+[3,4] === [1,2,3,4]
    

    So something like this should work (but!):

    var a=[1,2];
    var b=[3,4];
    a=a+','+b; // [1,2,3,4]
    

    ... but it will convert the variable a from an Array to String! Keep it in mind.

    0 讨论(0)
  • 2020-11-22 17:28

    It adds the two arrays as if they were strings.

    The string representation for the first array would be "1,2" and the second would be "3,4". So when the + sign is found, it cannot sum arrays and then concatenate them as being strings.

    0 讨论(0)
  • 2020-11-22 17:28

    The + concats strings, so it converts the arrays to strings.

    [1,2] + [3,4]
    '1,2' + '3,4'
    1,23,4
    

    To combine arrays, use concat.

    [1,2].concat([3,4])
    [1,2,3,4]
    
    0 讨论(0)
  • 2020-11-22 17:29

    [1,2]+[3,4] in JavaScript is same as evaluating:

    new Array( [1,2] ).toString() + new Array( [3,4] ).toString();
    

    and so to solve your problem, best thing would be to add two arrays in-place or without creating a new array:

    var a=[1,2];
    var b=[3,4];
    a.push.apply(a, b);
    
    0 讨论(0)
  • 2020-11-22 17:37

    In JavaScript, the binary addition operator (+) performs both numerical addition and string concatenation. However, when it's first argument is neither a number nor a string then it converts it into a string (hence "1,2") then it does the same with the second "3,4" and concatenates them to "1,23,4".

    Try using the "concat" method of Arrays instead:

    var a = [1, 2];
    var b = [3, 4];
    a.concat(b) ; // => [1, 2, 3, 4];
    
    0 讨论(0)
提交回复
热议问题