Javascript method Array.slice: subtleties of use

Table of contents:

Javascript method Array.slice: subtleties of use
Javascript method Array.slice: subtleties of use
Anonim

Arrays in the javascript language have many specific useful methods that make it easier to manipulate data. Some of these functions modify the original object, others create modified or exact copies. The last group includes the useful Array.slice() method. It allows you to select any subarray from an array and use it separately.

Method syntax


array.slice([begin[, end]])

As you can see, the method takes two arguments, but neither is required.

The first parameter indicates the position of the searched subarray, the second - the position of the element at which the extraction will be terminated. Therefore, they must be integers.

If there is no argument

end the method will work until the very end of the original array.

If both parameters are missing

array - it will simply be copied completely.

The function can also take negative arguments, while the position count will start from the end of the array.

Work examples

Let's consider the operation of the

slice() method on the example of a simple array of numbers:


let arr=[5, 4, 3, 2, 1];

Receivesubarray of the first three elements:


console.log(arr.slice(0, 3));

Here, the first argument is 0. It tells the function to start from position zero. And the second - 3, says that you need to stop at the element with index 3, not including it in the final selection. As a result, an array will be displayed on the console, including the numbers 5, 4 and 3.

array.slice() method
array.slice() method

Getting a subarray of the last three elements:


console.log(arr.slice(-3));

To perform this task, only one argument is needed, which will indicate the beginning of the sample. A negative value starts counting from the end of the array. In our case, this is the element with the value 3. The resulting array includes the numbers 3, 2, 1.

Return value

A feature of the javascript method

array.slice

() is that it does not modify the object in the context of which it was called. This means that after all the operations performed, the

arr array remained unchanged and can be used by the program for other purposes.

The function's job is to create a new array, not related to the original one, and fill it with the selected elements. In order for this array to be used later, it must be written to a variable.


let arr=[5, 4, 3, 2, 1]; let newArr=arr.slice(1, 4); console.log(newArr); // [4, 3, 2] console.log(arr); // [5, 4, 3, 2, 1]

The example shows that the object

arr

remains unchanged. The result of the method was a new array

newArr.

array.slice() method
array.slice() method

Copy arrays

This mechanism allows you to automatically create copies without manually going through each element of the sequence.


let clone=arr.slice(); console log(clone); // [5, 4, 3, 2, 1]

A method call with no arguments starts copying from the very beginning to the end of the array

arr. The resulting clone is completely independent of its source and allows you to manipulate data without fear of losing it forever.


clone[2]++; console log(clone); // [5, 4, 4, 2, 1] console.log(arr); // [5, 4, 3, 2, 1]

It's important to remember here that objects in javascript are passed by reference. Therefore, if the elements of the sequence are objects, then changing them in the copy will entail the same change in the source.


let arr=[{a: 1}, [2, 3]]; // copy the original array let newArr=arr.slice(); console.log(newArr); // [{a: 1}, [2, 3]] // modify the copy newArr[0].a=7; console.log(newArr); // [{a: 7}, [2, 3]] // original array has changed too console.log(arr); // [{a: 7}, [2, 3]]

You can safely work with strings, numbers and boolean values, as they are completely copied into the new sequence.

At the same time, adding and removing elements within the cloned array does not affect the original one.

Popular topic

Editor's choice

  • The PHP mail function: description, application features
    The PHP mail function: description, application features

    E-mail is an integral part of any modern project or business. Nowadays, speed and responsiveness are of great value, especially when it comes to customer feedback. This is a decisive factor that users consider when making purchases

  • Shareware - what is it List of programs, description of programming principles
    Shareware - what is it List of programs, description of programming principles

    Shareware has battled the stigma of misunderstanding for decades. While enterprise software giants can no longer ignore the marketing potential of a trial, small startups still struggle with new software challenges and costs

  • What is var in Pascal
    What is var in Pascal

    Variable var is a name that the user assigns to computer memory cells and uses to store values in a computer program. It defines the type of information stored, describes the format of the value of the occupied memory and methods for manipulating the content

  • Java library: creating, processing, working with files
    Java library: creating, processing, working with files

    Experienced Java developer has extensive knowledge of APIs including JDK, libraries for everyday projects including Log4j, JSON parsing, Jackson. The problem is that not all Java library designers think about their users, how the API will be used in practice, and how the code will look and be tested

  • Compression algorithms: description, basic techniques, characteristics
    Compression algorithms: description, basic techniques, characteristics

    Currently, processor processing power is increasing faster than storage capacity and network bandwidth. Therefore, in order to compensate for the increase in the amount of data, they compress them. The compressor uses an optimization algorithm of the appropriate type. For subsequent recovery, a decompressor with the opposite direction of the process is required