Array slice() Method - Javascript Array

Javascript examples for Array:slice

Description

The slice() method selects items from start to end.

The original array will not be changed.

Syntax

array.slice(start, end)

Parameter Values

Parameter Description
start Optional. starting index
end Optional. ending index.

The first element has an index of 0.

Using start in negative numbers to select from the end of an array. If omitted, it acts like "0"

If end is omitted, all elements from the start position and to the end of the array will be selected.

Use negative ending index numbers to select from the end of an array.

Return Value:

A new Array, containing the selected elements

The following code shows how to extract the third and fourth elements, using negative numbers.

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {//w  w w.  j av  a2 s . c om
    var fruits = ["A","B","C","D","E"];
    var myBest = fruits.slice(1, 3);
    document.getElementById("demo").innerHTML = myBest;
}
</script>

</body>
</html>

Related Tutorials