Why can't I concatenate an array reference in JavaScript?

I have two arrays, one of which is the link (parameter) from the function, and the other is created as part of the function - exactly the same as described here:

Add two arrays without using concat method

I used the push.apply () method as suggested above, but can someone explain to me why I cannot use concat () to combine two arrays if the array is sent to the function as a reference?

+4
source share
2 answers

Refer to Array.concat in MDN:

Any operation on a new array will not affect the original arrays and vice versa.

This makes it behave differently than Array.push.apply , which will mutate the original Array object — the return value of Array.concat should be used. Otherwise, it works as described in the MDN link above.

+8
source

If you use concat , the original array will be unmodified. If you have a link to it, you will not see new elements.

 var arr1 = [ "a", "b" ]; var arr2 = [ "c", "d" ]; arr1.push.apply(arr1, arr2); 

Mainly:

 [ "a", "b" ].push("c", "d"); 

apply turns an array into a list of arguments. The first argument to apply is context , by the way, arr1 in this case, since you want push to apply to arr1 .

You can use concat :

 var arr1 = [ "a", "b" ]; var arr2 = [ "c", "d" ]; var arr3 = arr1.concat(arr2); 

This leaves the original arr1 as it was. You have created a new array with two elements arr1 and arr2 . If you have a link to the original arr1 , it will not be changed. This may be a reason not to want to use concat .

+6
source

Source: https://habr.com/ru/post/1482044/


All Articles