This is very useful when you want to get the last element of the array, and then you just have to use -1. If we have given -2, it will return only. This will start counting from the end of the array and slice it (not the beginning from the array). In the above example, we have added a single argument as -3. Let slicedArray = favoriteFood.slice( -3) Let's see how this works with the below example. This array slice returns a new array with □ and □.Īnother thing that we can do with the slice() method is that use negative numbers for arguments. In this case, it will grab only up to index 2. Instead, it only includes the elements up to that index. But it doesn't include the index when slicing the array. As the second argument, we have added index 3.Remember that the first argument includes the index itself when slicing the array. We have added index 1 as the first argument.Let slicedArray = favoriteFood.slice( 1, 3) Imagine that we want to copy only the □ and □ from our previous example to a new array. Let's move on to slicing an array by passing two arguments. Here's a visual representation of our example: So in our example, we have made a copy from index 1 to favoriteFood.length - 1. When you pass a single argument to the slice() method, it grabs all the elements from that argument until the end of the array, including the index in the argument. Let slicedArray = favoriteFood.slice( 1) Ĭonsole.log(slicedArray) // Now let's check how we can slice an array with a single argument. So if you check their equality as in the example, it will return false. One important thing to note here is that these two arrays are not equal! They are two separate arrays containing the same values inside them. In the above example, since there are no arguments, it has returned a copy of the entire array. Let's slice an array with no arguments: let favoriteFood = Ĭonsole.log(slicedArray) // console.log(favoriteFood = slicedArray) //false If the endIndex value is omitted, it will slice to the end of the array.So, for example, adding index 4 will slice up to index 3, omitting the value of index 4.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |