Array splicing is often used in JavaScript. Both push and concat can merge arrays. What is the difference between them? Next, I will tell you the difference between JS array merge push and concat. Students in need can refer to it.
1. push() method
var array=[1,2,3,4,5]; console.log(array); //[1, 2, 3, 4, 5] array.push(6); //一个参数 console.log(array); //[1, 2, 3, 4, 5, 6] array.push(6,7); //两个参数 console.log(array); //[1, 2, 3, 4, 5, 6, 7] array.push([6,7]); //参数为数组 console.log(array); //[1, 2, 3, 4, 5, 6, Array(2)]
2. concat() method
var array=[1,2,3,4,5]; console.log(array); //[1, 2, 3, 4, 5] var array2=array.concat(6); //一个参数 console.log(array); //[1, 2, 3, 4, 5] console.log(array2); //[1, 2, 3, 4, 5, 6] var array2=array.concat(6,7); //两个参数 console.log(array); //[1, 2, 3, 4, 5] console.log(array2); //[1, 2, 3, 4, 5, 6,7] var array2=array.concat([6,7]); //参数为数组 console.log(array); //[1, 2, 3, 4, 5] console.log(array2); //[1, 2, 3, 4, 5, 6, 7]
You can see it through the code Several differences:
1, push() is modified on the basis of the original array, and the value of the original array will also change after executing the push() method; concat() first changes the Copy the original array to a new array, and then operate on the new array, so the value of the original array will not be changed.
2. If the parameter is not an array, no matter how many parameters there are, push() and concat() will directly add the parameters to the array; if the parameter is an array, push() will directly add the parameters to the array. After the array is added to the original array, concat() will take out the values in the array and add them to the original array.
Summary:
If you want to append to the array, use concat, but it is the same as Java's replace. Remember arr1=arr1.concat(arr2) after use. I hope this article will be helpful to everyone in JavaScript programming.
The above is the detailed content of In-depth understanding of the difference between JS array merge push and concat. For more information, please follow other related articles on the PHP Chinese website!