![]() ![]() The slice() method will not copy the element in this index. startIndex indicates where to begin copying elements.It takes in two parameters: startIndex( optional) and endIndex( optional).The original array remains the same ( it doesn't get modified).This method copies a specific range of elements into a new array.We can also get the values we removed with splice() by storing them in a variable: // based on Example 3 const deletedGadgets = gadgets.splice( 3, 2) Īrray.slice() Syntax Array.slice(startIndex, endIndex) Printed the gadgets array to the console in its current state.Removed two elements from our updated gadgets array from index 3. ![]() Starting from index 3 in our updated gadgets array, Printed our updated gadgets array to the console.Added 'smart watch' to the array at index 5.Removed one element from our updated gadgets array, starting from index 5.Starting from index 5 in our updated gadgets array, We printed our updated gadgets to the console.The second parameter - 0 - means no existing element of the array gets replaced.Inserted 'solar lamp', 'clock', and 'watch' in the gadgets array, starting from index 3.-> print to console console.log(gadgets) Gadgets.splice( 3, 0, 'solar lamp', 'clock', 'watch') Our initial array // = () = // INITIAL ARRAY const gadgets = newElement contains any element(s) to add to the array from the startIndex.deleteCount indicates how many elements to remove from the array.startIndex indicates which index of the array to start from.It takes in three parameters: startIndex, deleteCount( optional), and newElement( optional).This method modifies an existing array.In this article, we will look at these two array methods, understand how they work, and know when to use each one.Īrray.splice() Syntax Array.splice(startIndex, deleteCount, newElement) While working with arrays, most developers often find it challenging to differentiate between () and ().
0 Comments
Leave a Reply. |