What is array splice in javascript?

 array splice method javascript:

 

splice() method we use for removing and adding new elements on the existing array. The splice method has three parameters:

First is the indicating position of the element.

The second is indicating deleteCount.

The third is adding elements.

Syntax of splice method:

array.splice(startPosition, removeCount, addingElements)

If we will use a minimum of one parameter then will work only related to one parameter and rest parameter omitted then no will work.

 

Splice example in javascript:

 

const colors = ["Red", "blue", "Black", "Orange", "White", "Coffee"];

colors.splice(1, 0, 'Green');

// inserts at index 1 will not remove any color

console.log(colors);

//  Array ["Red", "Green", "blue", "Black", "Orange", "White", "Coffee"]

 

colors.splice(5, 1, 'purple');

// replace 1 element at index 5

console.log(colors);

// Array ["Red", "Green", "blue", "Black", "Orange", "purple", "Coffee"]

 

colors.splice(4);

// only show 4 elements

console.log(colors);

// Array ["Red", "Green", "blue", "Black"]




No comments:

Note: Only a member of this blog may post a comment.

Copyright Reserved to Anything Learn. Powered by Blogger.