![]() ![]() ![]() In this post, we had a quick overview of the differences between array.splice() and array.slice() and then looked at a few examples of their usage. Our warmColors array will contain the first three colors: Red,Orange,Yellow Conclusion We can slice the first three colors into a new array: let warmColors = colors.slice(0, 3) Imagine that we now want an array of just the warm colors in our colors array. Let’s assume that our array is reset to the original array we defined and use the slice() method to create a subset of that array. We can see that “Orange Yellow” is now gone from our array: Red,Orange,Yellow,Green,Blue,Violet,White,Black,Gray,Brown Removing with array.slice() Let’s remove the “Orange Yellow” value that we added to our array: colors.splice(2, 1) ![]() Since this is the functionality most likely to be confused with slice(), let’s now look at removing values with splice(). Now our array looks like this: Red,Orange,Orange Yellow,Yellow,Green,Blue,Violet,White,Black,Gray,Brown Removing with array.splice() Let’s use splice() to replace “Purple” with “Violet”: colors.splice(6, 1, 'Violet') Our array now contains “Orange Yellow”: Red,Orange,Orange Yellow,Yellow,Green,Blue,Purple,White,Black,Gray,Brownīy taking advantage of the second parameter, we can use splice() to replace values in our array. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |