slice()
Array
instance method getterS2C Home
« Globals « Array « slice()
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
begin
Negative values start extraction from the end of the index backwards, for the number after negation.
end
The ending position pertains to 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);
Related Tutorials
JavaScript Intermediate Tutorials - Lesson 1 - Arrays