Blog

Splice function in JavaScript

The splice function in JavaScript is used for adding, removing and returning elements from an array.
Let us suppose we have an array
var a=new Array(1,2,3,4,5);

  1. Splice with one parameter:
    This returns the elements of the array starting at the parameter.
    var b=a.splice(0);
    b=1,2,3,4,5.
    a=var b=a.splice(2):
    b=3,4,5
    a=1,2
  2. Splice with 2 parameters
    var a = Array(1, 2, 3, 4, 5);
    var b = a.splice(0,1);
    1st parameter is start=0
    and
    2nd parameter=1
    alert(b);
    alert(a);b=1
    and
    a=2,3,4,5
  3. Splice with 3 parameters
    var a = Array(1, 2, 3, 4, 5);
    var b = a.splice(0,2,”Popat”,”Apple”);
    alert(b);
    alert(a);The 1st parameter is start location =0
    2nd parameter is length=2
    remaining parameters are replacements: “Popat” and “Apple”So b will be 1,2
    and
    a=”Popat”,”Apple”,3,4,5

Leave a Reply

Your email address will not be published. Required fields are marked *