splice()  Array  instance method JS Home  <<  JS Reference  <<  Array  <<  splice()

Description

Adds and/or removes elements from within an array.

Syntax

Signature Description
anArray.splice(index [,integer] [,element1[, ...[, elementN]]])Adds and/or removes elements from within an array.

Parameters

Parameter Description
indexThe index at which to start modifications from or number of elements from the end for negative values.
integerAn integer indicating how many elements to remove or 0 for no removal. If not specified all elements after index will be removed.
elementNAny elements to add to the array.

Examples

The code below creates an array then adds and removes elements as per the comments.



// Create an array with four elements.
var weekDays = ['Mon', 'Tues', 'Wed', 'Thurs'];

/*
 Remove element 2 and 3 from the array using the splice() method. The first 
 number within the brackets is the starting index to delete from, remember
 indexing starts from 0. The second number is number of elements to delete.
 */
weekDays.splice(1,2);
alert(weekDays); // Array now holds ['Mon', 'Thurs'].

// Add two elements starting from index 1 splice() method. 
weekDays.splice(1,0,'Sat','Sun');
alert(weekDays); // Array now ['Mon', 'Sat', 'Sun', 'Thurs'].

/*
 Remove element 2 and 3 from the array and replace with new values using the 
 splice() method.
 */
weekDays.splice(1,2,'Tues','Wed');
alert(weekDays); // Array is ['Mon', 'Tues', 'Wed', 'Thurs'].

/*
 Only first parameter entered so all elements after index removed using the 
 splice() method.
 */
weekDays.splice(1);
alert(weekDays); // Array is ['Mon'].

Press the button below to action the above code:

Related Tutorials

JavaScript Intermediate Tutorials - Lesson 1 - Arrays

JavaScript Basics

JavaScript Basics

JavaScript Intermediate

JavaScript Intermediate

JavaScript Advanced

JavaScript Advanced

JavaScript Reference

JavaScript Entities

Globals

Array

Class Properties
prototype
Instance Properties
constructor
length
Class Methods
None.
Instance Methods Getters
concat()
join()
slice()
toString()
Instance Methods Setters
pop()
push()
reverse()
shift()
sort()
splice()
unshift()

Statements

Operators