js删除数组中已知下标的元素

假设数组arr有n个元素,现在要删掉下标为index的元素

有两种方法:

1.splice:删除后,后面的元素自动填补到前面

arr.splice(index, 1);

例子://arr=['a','b','c','d']

arr.splice(1, 1);//结果arr=['a','c','d'](下标1开始,删除1个)

补充:

spice增加:arr.splice(1,0,'str'); //结果arr=['a','str','b','c','d']

spice替换:arr.splice(1,1,'str'); //结果arr=['a','str','c','d']

spice替换2:arr.splice(1,2,'str'); //结果arr=['a','str','d'](就是说:下标1开始2个换成1个“str”)

spice删除多个:arr.splice(1,2); //结果arr=['a','d']

2.delete:删除后,该下标位置元素为undefined

delete arr[index];

//结果arr=['a',undefined,'c','d']

你可能感兴趣的:(javascript)