slice
can be invoked on an array and it accepts 2 arguments - startIndex
i endIndex
. It returns copy of an original array consisting of elements starting from startIndex
and ending on endIndex
(excluding endIndex
element).
If endIndex
was not passed, returned list will contain all elements from startIndex
to an end.
Negative indexes will cause counting from the end
slice
doesn't modify original list - it returns copy!
const list = ["a", "b", "c"]; console.info(list.slice(0, 2)); // ["a", "b"] console.info(list.slice(1)); // ["b", "c"] console.info(list.slice(4)); // [] console.info(list.slice(0, -1)); // ["a", "b"] console.info(list.slice(-2)); // ["b", "c"] console.info(list); // ["a", "b", "c"]
splice
can be invoked on an array and it accepts arguments startIndex
, deleteCount
and ...additionalElements
.
deleteCount
items will be removed from original list starting from startIndex
.
If deleteCount
wasn't passed, all elements from startIndex
to the end will be removed
Every next argument is a value which will be added in place of removed items
Negative startIndex
value will cause counting from the end
splice
modifies original array!
const list1 = ["a", "b", "c"]; const list2 = ["a", "b", "c"]; const list3 = ["a", "b", "c"]; console.info(list1.splice(0, 2)); // ["a", "b"] console.info(list1); // ["c"] console.info(list2.splice(1, 1, "d")); // ["b"] console.info(list2); // ["a", "d", "c"] console.info(list3.splice(-3, 1, "d")); // ["b"] console.info(list3); // ["d", "b", "c"]