JavaScript: Array.prototype.slice
The “slice” function lets you extract a sub-array from a array.
arrayX.slice()
- Return a copy of array. Original array is not modified.
arrayX.slice(start)
- Start at index start.
arrayX.slice(start, end)
- End at end but does not include end.
// take a sub list, starting with index 1 const r1 = [3,4,2]; const r2 = r1.slice(1); console.log( r1); // [3,4,2] console.log( r2); // [4,2]
// extract a sub array, from index 1 to 2 (excludes element at index 2) const r1 = ["a","b","c","d"]; const r2 = r1.slice(1,2); console.log( r1); // ["a","b","c","d"] console.log( r2); // ["b"]
// Array.prototype.slice can be used on array-like object to convert it to array const r1 = {"0":"a", "1":"b", "length":2}; const r2 = Array.prototype.slice.call(r1,0,3); console.log( r1); // { '0': 'a', '1': 'b', length: 2 } console.log( r2); // [ 'a', 'b' ]