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);".
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);
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);
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!