- var array1 = [1, 2];
- var array2 = [3, 4, 5];
- Version ≥ 3
- var array3 = array1.concat(array2); // returns a new array
- Version ≥ 6
- var array3 = [...array1, ...array2]
Concatenating Arrays JavaScript |
---|
Two Arrays
Results in a new Array: [1, 2, 3, 4, 5]
Multiple Arrays
Provide more Array arguments to array.concat()
Provide more arguments to []
Results in a new Array:
Without Copying the First Array
Provide the elements of shortArray as parameters to push using Function.prototype.apply
Use the spread operator to pass the elements of shortArray as separate arguments to push
The value of longArray is now:
Note that if the second array is too long (>100,000 entries), you may get a stack overflow error (because of how apply works). To be safe, you can iterate instead:
Array and non-array values
Results in a new Array:
You can also mix arrays with non-arrays
Results in a new Array:
Noted that: Above full tutorial makes good |
Published: | December 31, 2022 |
Author: | admin |
Category: | Javascript Source Code |
Views: | 22 |
This article was posted in Javascript Source Code. Bookmark the permalink. Follow comments with the RSS feed for this post.Post a Comment or leave a trackback: Trackback URL.
|
|