JS: 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.
Can be used on Array-Like Object to convert it to array.
// convert array-like object to array const xx = { "0": "a", "1": "b", "length": 2 }; const yy = Reflect.apply(Array.prototype.slice, xx, []); console.log(JSON.stringify(xx) === `{"0":"a","1":"b","length":2}`); console.log(JSON.stringify(yy) === `["a","b"]`);
arrayX.slice(start)
-
Start at index start.
// take a subarray, starting with index 1 const xx = ["x0", "x1", "x7"]; const yy = xx.slice(1); console.log(JSON.stringify(xx) === `["x0","x1","x7"]`); console.log(JSON.stringify(yy) === `["x1","x7"]`);
arrayX.slice(start, end)
-
End at end but does not include end.
// extract a subarray, from index 1 to 2 const xx = ["x0", "x1", "x2", "x3"]; const yy = xx.slice(1, 2); console.log(JSON.stringify(xx) === `["x0","x1","x2","x3"]`); console.log(JSON.stringify(yy) === `["x1"]`);