Thursday, 7 December 2017

JavaScript | Array.splice()

The splice() method adds/removes items to/from an array, and returns the removed item(s).

This method changes the original array.

It can take n number of arguments.

Syntax
array.splice(index, howmany, item1, ....., itemX)

index: Index, Required. An integer that specifies what position to add /remove items. Use negative values to specify the position at the end of the array.

howmany: Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from the provided index will be removed.

item1… X: Optional. The new items to be added to the array.

var array=[1,2,3,4,5];
var splicedArray = array.splice(2);
Output:
console.log(array);
[1, 2]

console.log(splicedArray);
[3, 4, 5]

var array2=[6,7,8,9,0];
console.log(array2.splice(2,1));
Output:
[8]

console.log(array2.splice(2,0));
Output:
[] , as no item(s) removed.

console.log(array2);
Output:
[6,7,9,0]

var array3=[11,12,13,14,15];
console.log(array3.splice(2,1,"Algos","Debug"));
Output:
[13]

console.log(array3);
Output:
[11, 12, "Algos", "Debug", 14, 15]



No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...