Home >Web Front-end >JS Tutorial >What are the methods to create arrays in javascript
There are several ways to create arrays in JavaScript: Use square brackets [] to create a literal array. Call the Array constructor. Create an array from an iterable object (e.g. string, array). Concatenate arrays using the concat() method. Use the spread operator (...) to spread one array into the elements of another array.
Methods to create arrays in JavaScript
In JavaScript, there are several ways to create arrays:
1. Literal syntax
This is the simplest method, use square brackets []
to create an array:
<code class="javascript">const myArray = [];</code>
2. Array constructor
Another way is to use the Array
constructor:
<code class="javascript">const myArray = new Array();</code>
3. Create from an iterable object
Arrays can be created from strings, arrays, or other iterable objects:
<code class="javascript">const myString = "Hello"; const myArray = Array.from(myString); // ["H", "e", "l", "l", "o"]</code>
4. Merging arrays
can be done using concat()
Method combines two or more arrays:
<code class="javascript">const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const mergedArray = array1.concat(array2); // [1, 2, 3, 4, 5, 6]</code>
5. Expansion operator
Expansion operator (...
) can be used to expand an array into elements of another array:
<code class="javascript">const array1 = [1, 2, 3]; const array2 = [...array1, 4, 5, 6]; // [1, 2, 3, 4, 5, 6]</code>
The above is the detailed content of What are the methods to create arrays in javascript. For more information, please follow other related articles on the PHP Chinese website!