Home >Web Front-end >Front-end Q&A >How to get the first few elements of an array in es6

How to get the first few elements of an array in es6

青灯夜游
青灯夜游Original
2022-05-05 16:14:2610822browse

es6 Two ways to get the first few elements of an array: 1. Use splice() to intercept array fragments to get the first N array elements. The syntax is "array object.splice(0,N)"; 2. . Use slice() to intercept array fragments. The syntax "array object.slice(0,N)" can obtain the first N array elements.

How to get the first few elements of an array in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

In es6, you can use the following two methods to intercept an array and get the first few elements of the array

  • splice()

  • slice()

1. Use splice() to intercept the array

The splice() method can add elements, delete elements, or Intercept array fragments. When an element is deleted, the deleted array fragment will be returned, so the splice() method can be used to intercept the array fragment.

Example 1: Intercept the first two elements of the array

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
console.log(fruits);
var citrus = fruits.splice(0,2);
console.log("数组前两个元素:"+citrus);

How to get the first few elements of an array in es6

Example 2: Intercept the first three elements of the array

var citrus = fruits.splice(0,3);
console.log("数组前3个元素:"+citrus);

How to get the first few elements of an array in es6

2. Use slice() to intercept the array

The slice() method has similar functions to the splice() method, but it can only intercept the elements of the specified section in the array. , and return this subarray. This method contains two parameters, specifying the subscripts of the starting and ending positions of the intercepted subarray.

You only need to set the first parameter to 0 and the second parameter to the specified N digits to get the first N elements of the array.

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
console.log(fruits);
console.log("数组前1个元素:"+fruits.slice(0,1));
console.log("数组前2个元素:"+fruits.slice(0,2));
console.log("数组前3个元素:"+fruits.slice(0,3));

How to get the first few elements of an array in es6

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of How to get the first few elements of an array in es6. 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