archivepolew.blogg.se

Slice array javascript
Slice array javascript






When you build your own module, it is important to choose an API which minimizes this slice vs splice confusion. This is not supposed to be a surprise, after all the name splice implies it. On top of that, splice also mutates the array that calls it. var x = Īlthough splice (Section 15.4.4.12) also takes two arguments (at minimum), the meaning is very different. As you can see, x keeps its elements and y gets the sliced version thereof. The following code fragment illustrates the behavior. It’s not very difficult to understand what slice does: 'abc'.slice(1,2) // "b"Īn important aspect of slice is that it does not change the array which invokes it. It will return a new array containing the elements from the given start index up the one right before the specified end index. According to the specification, slice needs to accept two arguments, start and end. In practice, such a confusion can be avoided by choosing an API that telegraphs the const-correctness of the function.Īrray’s slice (ECMAScript 5.1 Specification Section 15.4.4.10) is quite similar to String’s slice. These two functions, although they have similar names, are doing two completely different things. In JavaScript, mistaking slice for splice (or vice versa) is a common mistake among rookies and even experts. And you're equipped with a handy mnemonic, that splice compared to slice has an additional letter, 'p', which helps you remember that splice mutates and optionally adds or removes from the original About Talks Articles JavaScript Array: slice vs splice You now know that slice makes a shallow copy of the original array, while splice mutates the original array and optionally adds or removes elements. ConclusionĪnd there we have it! This blog goes over the differences between slice and splice. And because splice can add and remove stuff to the original array, that means that it also mutates the original array.

slice array javascript

Because of the extra letter, I associate the additional letter to splice's use of adding or removing from the original array. splice has an extra letter, 'p', compared to slice. I remember the difference between slice and splice using a mnemonic.

slice array javascript slice array javascript

insert 'juliet' and 'zeke' at 3rd index // returns Ĭonsole. splice ( 3, 1, 'juliet', 'zeke' ) // remove 'harper'.








Slice array javascript