.splice(index to start,Number of element to delete)
The easiest way to empty an array is by setting its length to 0
const apples = ['red apple', 'green apple', 'yellow apple', 'Mac']
apples.length = 0
// return apples = []
We may also use
const apples = ['red apple', 'green apple', 'yellow apple', 'Mac']
apples.splice(0)
// return apples = empty array[]
If we want delete the first apple
const apples = ['red apple', 'green apple', 'yellow apple', 'Mac']
apples.splice(0,1)
// return apples = [ 'green apple', 'yellow apple', 'Mac' ]
If we want delete the second apple
const apples = ['red apple', 'green apple', 'yellow apple', 'Mac']
apples.splice(1,1)
// return apples = [ 'red apple', 'yellow apple', 'Mac' ]
If we want delete the second and third apples
const apples = ['red apple', 'green apple', 'yellow apple', 'Mac']
apples.splice(1,2)
// return apples = [ 'red apple', 'Mac' ]
Top comments (2)
what about assigning it to an empty array
apples = [];
const apples = ['red apple', 'green apple', 'yellow apple', 'Mac']
apples.splice(0,0, 'Japan apple') // I add a 'Japan apple' in index[0], and I wan't remove anythings.
now apples is [ 'Japan apple', 'red apple', 'green apple', 'yellow apple', 'Mac' ]
I want treate this topic in another article.
have a nice day