Middle+
Mida teeb meetod Array.prototype.slice? Kuidas seda kasutatakse massiivi kopeerimiseks?
sobes.tech AI
Vastus AI-lt
Array.prototype.slice() method returns a new array containing a copy of a portion of the original array, starting from the begin index and up to (but not including) the end index. If parameters are not provided, the entire array is copied.
To copy an array without modifications, you can call slice() without arguments:
const original = [1, 2, 3];
const copy = original.slice();
console.log(copy); // [1, 2, 3]
console.log(copy === original); // false — this is a new array
Thus, slice() is used for shallow copying of an array, which is useful when you want to create a new array with the same elements without changing the original.