Home > Article > Web Front-end > How Can I Efficiently Extend a JavaScript Array In-Place?
Extending JavaScript Arrays: An In-Place Solution
Extending an existing JavaScript array with another array without creating a new one is not a straightforward operation. Unlike Python's extend method, JavaScript does not provide a built-in solution.
Fortunately, we can achieve this behavior efficiently using the .push() method in conjunction with the spread operator(...).
const a = [1, 2]; const b = [3, 4, 5]; a.push(...b);
The spread operator expands the elements of b into individual arguments, passing them to a.push(). This effectively adds the entire contents of b to a.
Alternatively, in older browsers that do not support ECMAScript 6, you can use the .apply() method:
a.push.apply(a, b);
However, this approach may fail due to stack overflow errors when the number of elements in b is excessive. In such cases, a traditional loop-based technique is recommended:
for (const element of b) { a.push(element); }
This ensures that the elements are appended to a one by one, avoiding the stack overflow issue.
The above is the detailed content of How Can I Efficiently Extend a JavaScript Array In-Place?. For more information, please follow other related articles on the PHP Chinese website!