JavaScript Array slice()Method

Array 对象参考手册JavaScript Array Object

Example

Read elements from an array:

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1,3);

citrusOutput:

Orange,Lemon

Try it Yourself »

Definition and Usage

The slice() method returns selected elements from an existing array.

The slice() method extracts a part of a string and returns the extracted part as a new string.

Note:The slice() method does not change the original array.


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support slice().


Syntax

array.slice(start, end)

Parameter Values

Parameter Description
start Optional. Specifies where to start the selection. If this parameter is negative, it indicates that extraction starts from the nth element from the end of the original array. slice(-2) extracts from the second-to-last element to the last element (including the last element).
end Optional. Specifies where to end the selection. This parameter is the array index at which the array slice ends. If this parameter is not specified, the sliced array contains all elements from start to the end of the array. If this parameter is negative, it indicates that extraction ends at the nth element from the end of the original array. slice(-2,-1) means extracting the second-to-last element to the last element (excluding the last element, i.e., only the second-to-last element).

Return Value

Type Description
Array Returns a new array containing the elements of arrayObject from start (inclusive) to end (exclusive).

Technical Details

JavaScript Version: 1.2


More Examples

Example

Read elements from an array using negative values

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var myBest = fruits.slice(-3,-1); //Extract the two elements from the third-to-last (inclusive) to the last (exclusive) var myBest = fruits.slice(-3); //Extract the last three elements

myBestOutput:

Lemon,Apple

Try it Yourself »

Example

Slice a string

var str="www.example.com!"; document.write(str.slice(4)+"<br>"); //Extract from the 5th character to the end document.write(str.slice(4,10)); //Extract from the 5th character to the 10th character

Try it Yourself »

Array 对象参考手册JavaScript Array Object

Other Extensions