Wednesday, 6 December 2017

JavaScript | Array slice() Method

The slice() method returns the selected elements in an array, as a new array object.

Syntax
array.slice(start, end)

start: An Optional integer that specifies where to start the selection. Use negative numbers to select from the end of an array. If omitted, it acts like "0".
end: An optional integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.

The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.

var employee = ["Algos", "Shanky", "Rob", "Paul"];
var best_emp = employee.slice(1, 3);

Output:
console.log(best_emp);
["Shanky", "Rob"]

Note: The original array will not be changed.

Example to select elements using negative values
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var myBest = fruits.slice(-3, -1);

Output:
console.log(myBest);
["Lemon","Apple"]

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...