The index of the last element is -1, and the index of second last element is -2, and so on. In JavaScript slice() method, you can use negative index for start and end parameters. Let almostFull = cars.slice(second, secondLast) slicing from the second element to second last element Let middleIndex = Math.floor(cars.length / 2) slicing the hole array from starting to end If start is omitted or undefined, slice starts from the index 0. splice() and slice() are one of the most useful array methods we have and Its not always easy to remember which. It copies the selected elements from the original array and returns them as a new array. slice(-3) extracts the last three elements in the sequance. JavaScript has a lot of built-in methods. The JavaScript slice () method is used to select a portion of an array. Negative index can be used, and it selects from the end of the array. Zero-based index at which to start extraction. JavaScript () Parameters start (optional) JavaScript () SyntaxĪs you can see you can use slice() method in multiple ways it depends on you how you want to use because as you have seen in above code you can use negative indexes as well to access the values of array to create your own new array as of needed.
0 Comments
Leave a Reply. |