Home  >  Article  >  Web Front-end  >  How Can I Efficiently Extend a JavaScript Array In-Place?

How Can I Efficiently Extend a JavaScript Array In-Place?

Susan Sarandon
Susan SarandonOriginal
2024-11-21 04:05:19733browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Running bolt.new LocallyNext article:Running bolt.new Locally