luxejas.blogg.se

Slice in javascript array
Slice in javascript array








slice in javascript array

I'm using `alert()` instead of `console.The `slice` method in JavaScript is a powerful tool for extracting portions of an array without modifying the original. slice(-2) extracts the last two elements in the sequence." Thus, your array.slice(-1) is returning a new array populated with the last element of your original, array. The documentation says that " negative index can be used, indicating an offset from the end of the sequence.

slice in javascript array

In your code, you are executing array.slice(-1). beginning at 1 and up to (not including) 3.Ĭonsole.log(array) // When you call array.slice(), that's returning a slice of your array (as another array).

slice in javascript array

That gives you the first (and only) item from the sliced array, which is then passed to the alert(.). Moving left-to-right, we now have an array of a single item followed by an array index. So, array.slice(-1) gives you an array containing the last element from the original array. slice(-2) extracts the last two elements in the sequence.Ī new array containing the extracted elements. Both function calls and member access are level 19, with left-to-right associativity, which means we evaluate the function call first, then the array index next.įor this, let's turn to the documentation on array.slice, which says:Ī negative index can be used, indicating an offset from the end of the sequence. Which is evaluated first? To answer this, we turn to Operator Precedence. It has one argument: array.slice(-1), which we'll examine next.Īrray.slice(-1) is another function call. Before it can execute (and print something to the screen), its arguments must be evaluated first. This is your original statement: alert(array.slice(-1)) Īlert(.) is a function call. By understanding each small piece, you will understand the whole. Break the expression down into its parts.










Slice in javascript array