JavaScript & jQuery Tutorials

JS Home Right Arrow JS Reference Right Arrow Array Right Arrow slice()

slice()  Array  instance method

Description

Returns a new array comprising of a single depth section of an existing array.

  • Any modifications to the new array has no affect on the arrays it was created from.
  • Any modifications to the old array has no affect on the new array created from them.
  • Modifications to an object whose reference is held within the arrays will affect both arrays.

Syntax


Signature Description
anArray.slice(begin[, end])Returns a new array comprising of a single depth section of an existing array.

Parameters


Parameter Description
beginThe starting extraction position of the zero-based index.
Negative values start extraction from the end of the index backwards, for the number after negation.
endThe ending extraction position of the zero-based index.
The ending position pertains to the index to stop before or for negative values the elements to miss from end.
When omitted extraction is to end of array.

Examples

The code below creates new arrays containing sections of the initial array.




// Create an array of days of the week.
var week = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'];

/*
 Create array of middle 3 days of week. 
 Slice stops after 5th elem. (Fri).
 var midDays = ['Wed', 'Thurs', 'Fri'];
 /*
var midDays = week.slice(2,5);

/*
 Create array of middle 3 days of week. 
 Slice misses last 2 elements.
 var middleDays = ['Wed', 'Thurs', 'Fri'];
 /*
var middleDays = week.slice(2,-2);

/*
 Create array of weekend days. 
 Slice will extract last 3 elements.
 var weekendDays = ['Fri', 'Sat', 'Sun'];
 /*

var weekendDays = week.slice(-3);
alert(midDays + ' - ' + middleDays + ' - ' + weekendDays);

Press the button below to action the above code:


Related Tutorials

JavaScript Intermediate Tutorials - Lesson 1 - Arrays



  

go to home page Homepage go to top of page Top