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

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

青灯夜游
Release: 2022-01-18 19:12:03
Original
32217 people have browsed it

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);
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template