slice&splice使用

发布时间 2023-06-02 10:08:50作者: Felix_Openmind

Slice array elements

Slice: To cut out a multiple items in range. It takes two parameters: starting and ending position
It doesn't inclue the ending position.

const numbers = [1, 2, 3, 4, 5]

console.log(numbers.slice()); // it copies all item

console.log(numbers.slice(0)); // it copies all item

console.log(numbers.slice(0, numbers.length)); // it copies all item

console.log(numbers.slice(1, 4)) // -> [2, 3, 4] it doesn't include the ending position

Splice methond in array

Splice: It takes three parameters: Starting position, number of times to be removed and number of items to be added.

const numbers = [1, 2, 3, 4, 5]
console.log(numbers.splice()); // remove all items
console.log(numbers.splice(0, 1)); // remove the first item