JavaScript·100 questions

QUESTION: Как работать с массивами?

Answer

Working with arrays in JavaScript is an everyday task for any developer, as arrays serve as the primary tool for storing ordered collections of data. There are many ways to create arrays and manage their contents depending on the current project tasks.

You can create an array using the square bracket literal [], the new Array() constructor, or the static Array.from() method, which converts iterable objects or array-like objects into a full-fledged array. Various built-in methods are used to modify the structure and contents of arrays.

The following approaches are used to modify elements:

The push and pop methods add and remove elements from the end of the array respectively, changing its length.
The shift and unshift methods perform the same operations on the beginning of the array, although operations at the beginning are slower on large volumes of data because they require shifting all elements.
To get a copy of a portion of an array without mutating it, the slice method is used, while splice allows you to remove, replace, or add elements at an arbitrary position.

To combine multiple arrays, you can use the concat method or the modern spread operator, denoted by three dots, which elegantly unpacks elements. To find elements in an array, the includes method is used (returning a boolean value depending on whether the element exists) and indexOf (returning the index of the first occurrence of the searched value).

Was this answer helpful?

More questions in this topic

Related questions from other topics