There are several ways to populate a JavaScript array:
- Add elements one by one using the array’s push() method:
let myArray = [];
myArray.push("element1");
myArray.push("element2");
- Use an array literal to define the elements when creating the array:
let myArray = ["element1", "element2"];
- Use a loop to add elements to the array:
let myArray = [];
for (let i = 0; i < 5; i++) {
myArray.push("element" + i);
}
- Use the array’s splice() method to insert new elements at a specific index:
let myArray = ["element1", "element3"];
myArray.splice(1, 0, "element2");
This will insert “element2” at index 1 of the array.
- Use the array’s concat() method to merge two or more arrays:
let myArray1 = ["element1", "element2"];
let myArray2 = ["element3", "element4"];
let myArray = myArray1.concat(myArray2);
+ There are no comments
Add yours