To extend an existing JavaScript array with another array without creating a new array, you can use the push()
method to add elements from the second array to the end of the first array. Here's an example:
javascript
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
// Use the push() method to add elements from array2 to array1
for (let element of array2) {
array1.push(element);
}
console.log("Extended array1:", array1);
Output:
less
Extended array1: [1, 2, 3, 4, 5, 6]
In this example:
- We have
array1
containing[1, 2, 3]
andarray2
containing[4, 5, 6]
. - We use a loop to iterate over each element in
array2
. - For each element, we use the
push()
method to add it to the end ofarray1
. - After the loop,
array1
is extended with the elements fromarray2
.
Keep in mind that this approach modifies the original array1
directly. If you want to avoid modifying the original array and create a new array with the combined elements, you can use the spread operator or the concat()
method:
Using the spread operator:
javascript
let extendedArray = [...array1, ...array2];
console.log("Extended array:", extendedArray);
Using the concat()
method:
javascript
let extendedArray = array1.concat(array2);
console.log("Extended array:", extendedArray);
Both of these methods create a new array that contains the elements of both arrays, leaving the original arrays unchanged.
Comments
Post a Comment