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

前端 未结 13 1658
小蘑菇
小蘑菇 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:47

    Some answers here have explained how the unexpected undesired output ('1,23,4') happens and some have explained how to obtain what they assume to be the expected desired output ([1,2,3,4]), i.e. array concatenation. However, the nature of the expected desired output is actually somewhat ambiguous because the original question simply states "I wanted to add the elements of an array into another...". That could mean array concatenation but it could also mean tuple addition (e.g. here and here), i.e. adding the scalar values of elements in one array to the scalar values of the corresponding elements in the second, e.g. combining [1,2] and [3,4] to obtain [4,6].

    Assuming both arrays have the same arity/length, here is one simple solution:

    const arr1 = [1, 2];
    const arr2 = [3, 4];
    
    const add = (a1, a2) => a1.map((e, i) => e + a2[i]);
    
    console.log(add(arr1, arr2)); // ==> [4, 6]

提交回复
热议问题