Home  >  Article  >  Web Front-end  >  How to get the first few elements of an array in javascript

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

青灯夜游
青灯夜游Original
2022-01-18 19:12:0332154browse

Javascript method to get the first few elements of an array: 1. Use slice() to intercept a specified number of elements from the array, the syntax is "array.slice(0, number of elements)"; 2. Use splice(), the syntax is "array.splice(0, number of elements);".

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

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Javascript method to get the first few elements of the array

1. Use slice()

## The #slice() method returns selected elements from an existing array.

The slice() method extracts a certain part of a string and returns the extracted part as a new string.

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

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

2. Use splice()

The splice() method is used to add or delete elements in the array.

The splice() method returns an array containing the deleted elements.

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

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

【Related recommendations:

javascript learning tutorial

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