So me and my peer discovered in our boot camp lab today that If you use the .splice() method on an array and want to use it to make a copy with an additional element at the end of the array ( exp. Arr.splice(start, deletecount, new element added).)
You kind of have to know the length of the array because it adds the new element to the left indexs of the specified starting point so .splice(-1,0,”newstring”)will add the new string an index before the final element in the array and not at the end of the array. Wild, just wild. Any comments to expand my understanding of this method is more than welcome.
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (5)
I'd argue that the best way to insert at the end of an array is
push
and at the start isunshift
.splice
is very handy when working with rearranging lists, drag and drop and the like as it can be applied anywhere within the list using the index of the insert before item.Negative indexing for "last items" is very helpful, and also works with
slice
to make an array from a source array. In the latest Javascript there is also theat
function which allows you to look up individual items using negative indexing.There's better ways to clone and append to an array than splice. Splice actually mutates the original array and I use it mainly to remove an element from an array. Could you explain why you want to use splice? For the sake of experimenting? With ES6 you can initiate a new array and use spread to create such an array.
Yeah I was just trying to better understand it’s functionality and this seemed like a small enough experiment to test the potential implementation. Definitely agree that your example using the spread operator is a much more practical approach.
For "cloning" objects JSON.stringify and JSON.parse can be used. Just wanted to mention it, but it does not work for all cases!