Q:

how to delete the array in javascript

//you can use two functions depending of what you want to do:

let animals1 = ["dog", "cat", "mouse"]
delete animals1[1]
/*this deletes all the information inside "cat" but the element still exists
so now you'll have this:*/
console.log(animals1)//animals1 = ["dog", undefined, "mouse"]

//if you want to delete it completely, you have to use array.splice:

let animals2 = ["dog", "cat", "mouse"]
animals2.splice(1, 1)
/*the first number means the position from which you want to start to delete
and the second is how much elements will be deleted*/
console.log(animals2)//animals2 = ["dog", "mouse"]
/*Now you don't have undefined
If you did this:*/
let animals3 = ["dog", "cat", "mouse"]
animals3.splice(0, 2)//you'll have this:
console.log(animals3)//animals 3 = "mouse"
/*This happens because I put a 2 in the second parameter so it deleted
two elements from position 0
Try copying this code in your console and whatch*/
3
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];var removed = arr.splice(2,2);/*removed === [3, 4]arr === [1, 2, 5, 6, 7, 8, 9, 0]*/
0
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];for( var i = 0; i < arr.length; i++){ if ( arr[i] === 5) { arr.splice(i, 1); }}//=> [1, 2, 3, 4, 6, 7, 8, 9, 0]
1
["bar", "baz", "foo", "qux"]list.splice(0, 2) // Starting at index position 0, remove two elements ["bar", "baz"] and retains ["foo", "qux"].
0

New to Communities?

Join the community