Array slice()
slice() returns the sub-array. The slice() method may accept one or two arguments:
- the starting
- stopping positions.
slice(startingPoint) returns sub-array between startingPoint and the end of the array. slice(startingPoint,endPosition) returns sub-array between the startingPosition and endPosition, not including the item in the end position.
slice() does not affect the original array in any way.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var colors = ["A", "B", "C", "D", "E"];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);
document.writeln(colors2); //B,C,D,E
document.writeln(colors3); //B,C,D
</script>
</head>
<body>
</body>
</html>
If either the start or end position of slice() is a negative number, then the number is subtracted from the length of the array.
arrayWithFiveItem.slice(-2, -1) is the same as arrayWithFiveItem.slice(3, 4).
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var colors = ["A", "B", "C", "D", "E"];
var colors2 = colors.slice(-2,-1);
var colors3 = colors.slice(3,4);
document.writeln(colors2); //D
document.writeln(colors3); //D
</script>
</head>
<body>
</body>
</html>
If the end position is smaller than the start, then an empty array is returned.
Home
JavaScript Book
Essential Types
JavaScript Book
Essential Types
Array:
- The Array Type
- Array Built-in Methods
- Detecting Arrays
- Get and set array values
- Enumerating the Contents of an Array
- Array Length
- Array join() method
- Array concat()
- Array indexOf()
- Array lastIndexOf()
- Array every()
- Array filter() filters array with the given function.
- Array map()
- Array forEach()
- push() and pop():Array Stack Methods
- push(), shift():Array Queue Methods
- Array reduce()
- Array reduceRight()
- reverse():Reordering array
- Array slice()
- Array some()
- Array splice()
- Array sort()
- toString(), toLocaleString() and valueOf Array
- Array unshift()