Home  >  Article  >  Common usage of Array.slice

Common usage of Array.slice

zbt
zbtOriginal
2023-11-27 10:55:431713browse

Common uses of Array.slice are to extract some array elements and copy an array. It should be noted that the Array.slice() method does not modify the original array, but returns a new array. The starting index is included in the result, while the ending index is not included in the result.

Common usage of Array.slice

The Array.slice() method is a method of the array object in JavaScript. It is used to extract or intercept elements from the array and return a new array. The following is the common usage of the Array.slice() method:

1. Extract some array elements

const fruits = ["apple", "banana", "orange", "grape", "mango"];
const citrus = fruits.slice(1, 3);
console.log(citrus); // Output: ["banana", "orange"]

In the above example, the slice() method extracts elements starting from index 1 (inclusive) until index 3 (exclusive). Therefore, it extracts the elements at index 1 and 2 in the array fruits and returns a new array containing these elements.

2. Copy an array

##

const originalArray = [1, 2, 3, 4, 5];
const copiedArray = originalArray.slice();
console.log(copiedArray); // Output: [1, 2, 3, 4, 5]

In this In the example, the slice() method takes no parameters and will return a copy of the original array, thus achieving a shallow copy of the array.

It should be noted that the Array.slice() method does not modify the original array, but returns a new array. The starting index is included in the result, while the ending index is not included in the result.

Also, if the arguments are negative, they represent positions starting from the end of the array. For example, -3 represents the third element from the bottom.

The above is the detailed content of Common usage of Array.slice. 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