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:
const myArray = [];
2. Array constructor
Another way is to use the Array
constructor:
const myArray = new Array();
3. Create from an iterable object
Arrays can be created from strings, arrays, or other iterable objects:
const myString = "Hello"; const myArray = Array.from(myString); // ["H", "e", "l", "l", "o"]
4. Merging arrays
can be done using concat()
Method combines two or more arrays:
const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const mergedArray = array1.concat(array2); // [1, 2, 3, 4, 5, 6]
5. Expansion operator
Expansion operator (...
) can be used to expand an array into elements of another array:
const array1 = [1, 2, 3]; const array2 = [...array1, 4, 5, 6]; // [1, 2, 3, 4, 5, 6]
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!