Home >Web Front-end >JS Tutorial >How to Retrieve the First N Elements from an Array in JavaScript?
Retrieving First N Elements from an Array
You can obtain the first N elements of an array in JavaScript by employing the slice method as follows:
<code class="js">const slicedArray = array.slice(0, n);</code>
For instance, if you have an array [1, 2, 3, 4, 5], and you want to get the first 3 elements, you would use:
<code class="js">const firstThree = [1, 2, 3, 4, 5].slice(0, 3); // [1, 2, 3]</code>
This method will return a new array containing the first N elements, without modifying the original array.
The above is the detailed content of How to Retrieve the First N Elements from an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!