JavaScript concat() method
Definition and usage
The concat() method is used to concatenate two or more arrays.
This method does not change the existing array, but returns a new array.
Purpose: Merge 2 or more arrays
Variable name | value1,value2,value3,…,valueN | |
---|---|---|
Detailed description | Value or array (object can be passed) | |
Is it necessary to pass | no |
Note that concat returns a shallow copy
Example:
1. Connect 2 arrays
const arr = [1, 2, 3].concat([4, 5]) (arr) // [1,2,3,4,5]
2. Connect 3 arrays
const arr1 = [1, 2] const arr2 = [3, 4] const arr3 = [5, 6] const arr4 = (arr2, arr3) (arr4) // [1, 2, 3, 4, 5, 6]
3.Connect values to array
const arr1 = [1, 2] const arr2 = 3 const arr3 = [5, 6] const arr4 = (arr2, arr3) (arr4) // [1, 2, 3, 5, 6]
Interesting knowledge
talk is cheap,show you my code
const arr1 = [[1]] const arr2 = [3, 4] const arr3 = [5, 6] const arr4 = (arr2, arr3) (arr4) // [[1], 3, 4, 5, 6] arr1[0].push(2) (arr4) // [[1, 2], 3, 4, 5, 6]
const arr1 = [1] const arr2 = [3, 4] const arr3 = [5, 6] const arr4 = (arr2, arr3) (arr4) // [1, 3, 4, 5, 6] (2) (arr4) // [1, 3, 4, 5, 6]
To put it simply, if there is a reference type in the connected array, then this reference type is shared. Actually, what I said at the beginning was a shallow copy, and you should understand it.
The object can be connected
const arr1 = [1] const arr2 = [3, 4] const arr3 = { a: 1, b: 2 } const arr4 = (arr2, arr3) (arr4) // [1, 3, 4, {a:1, b:2}]
The object has an attribute indicating whether to expand when using the concat method (note that it is expanded when used as a parameter)
- Arrays are expanded by default
- Objects are not expanded by default
Array expansion by default
const arr1 = [1] const arr2 = [3, 4] const arr3 = (arr2) (arr3) // [1, 3, 4] arr2Expanded
const arr1 = [1] const arr2 = [3, 4] arr2[] = false const arr3 = (arr2) (arr3) // [1,[3,4]] arr2Not expanded
Objects are not expanded by default
const arr1 = [1] const obj2 = { a: 1, b: 2 } const arr3 = (obj2) (arr3) // [1,{a:1, b:2}] Objects are not expanded by default
const arr1 = [1] const obj2 = { // Note that you need to add the length attribute in this place, if you want to expand it length: 2, 0: 2, 1: 3 } obj2[] = true const arr3 = (obj2) (arr3) // [1,2,3]
Concat method of string
Example
const str1 = 'aa' const str2 = ('bb') (str2) // aabb
This is the article about JavaScript's concat method example code(). For more related js concat content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!