plegm.blogg.se

Slice an array in javascript
Slice an array in javascript













In the above code the parameter passed to the slice( ) method is, for start index as -4 and end index as -1, so the slice( ) method slice the given array a or extract the elements of the given array from index -4 to index -1 (the end value is excluding), in the reverse order the last element is store at index -1, the last second element is store at index -2 and so all. In the next example code, we will rewrite the above code for the slice( ) method to extract the multiple elements from the given array based on the negative index.

slice an array in javascript

Hence in an array an at the index 1 it stores element “Banana”, at index 2 store element “Orange” and at index 3 store element “Mango”, So the return value of the slice method is “Apple, Orange, Mango”, as shown in the output. In the above code the parameter passed to the slice( ) method is for start index as 1 and end index 4, so the slice( ) method slice the given array a or extract the elements of the given array from index 1 to index 3 (the end value is excluding). In the next example code, we will rewrite the above code for slice( ) method to extract the multiple elements from the given array. Hence in an array an at the index 2 it stores element “Orange”, So the return value of the slice method is “Orange”, as shown in the output. In the above code the slice( ) method is using and the passed the parameter value for start index as 2 and end index 3, so the slice( ) method slice the given array a or extract the elements of the given array from index 2 to index 2 (the end value is excluding). Next, we will write the HTML code to understand the slice( ) method more clearly with the following example, the slice( ) method used to extract the single element from the array a bypassing the start index as 2 and end index 3.

slice an array in javascript slice an array in javascript

If we do not provide a value for this parameter, then the function takes the length of the array as the default value and if the end value is greater than the array length, then the end value takes as the length of the array. Note that the end index value is excluding means that the end value will be end-1value. If we do not provide a value for this parameter, then the function takes 0 as default value.Įnd – end parameter is an optional parameter, which is used to specify the ending index up to where the elements to be extracted. Start – start parameter is an optional parameter, which is used to specify the starting index from where the elements start to be extracted.















Slice an array in javascript