JS删除数组中元素

JavaScript013

JS删除数组中元素,第1张

1、splice

splice(index,len,[item])注释:该方法会改变原始数组。

splice有3个参数,它也可以用来替换/删除/添加数组内某一个或者几个值

index:数组开始下标len: 替换/删除的长度 item:替换的值,删除操作的话 item为空

如:arr = ['a','b','c','d']

删除 ---- item不设置

arr.splice(1,1) //['a','c','d'] 删除起始下标为1,长度为1的一个值,len设置的1,如果为0,则数组不变

arr.splice(1,2) //['a','d'] 删除起始下标为1,长度为2的一个值,len设置的2

替换 ---- item为替换的值

arr.splice(1,1,'ttt')//['a','ttt','c','d'] 替换起始下标为1,长度为1的一个值为‘ttt',len设置的1

arr.splice(1,2,'ttt')//['a','ttt','d'] 替换起始下标为1,长度为2的两个值为‘ttt',len设置的1

添加 ---- len设置为0,item为添加的值

arr.splice(1,0,'ttt')//['a','ttt','b','c','d'] 表示在下标为1处添加一项‘ttt'

看来还是splice最方便啦

2、delete

delete删除掉数组中的元素后,会把该下标出的值置为undefined,数组的长度不会变

如:delete arr[1] //['a', ,'c','d'] 中间出现两个逗号,数组长度不变,有一项为undefined

下面三种都会影响原数组,最后一项不影响原数组:

opop()

oshift()

osplice()

oslice()

1、pop()

pop() 方法用于删除数组的最后一项,同时减少数组的length 值,返回被删除的项

let colors = ["red", "green"]

let item = colors.pop()// 取得最后一项

console.log(item) // green

console.log(colors.length) // 1

2、shift()

shift()方法用于删除数组的第一项,同时减少数组的length 值,返回被删除的项

let colors = ["red", "green"]

let item = colors.shift()// 取得第一项

console.log(item) // red

console.log(colors.length) // 1

3、splice()

传入两个参数,分别是开始位置,删除元素的数量,返回包含删除元素的数组

let colors = ["red", "green", "blue"]

let removed = colors.splice(0,1)// 删除第一项

console.log(colors)// green,blue

console.log(removed)// red,只有一个元素的数组

4、slice()

slice() 用于创建一个包含原有数组中一个或多个元素的新数组,不会影响原始数组

let colors = ["red", "green", "blue", "yellow", "purple"]

let colors2 = colors.slice(1)

let colors3 = colors.slice(1, 4)

console.log(colors) // red,green,blue,yellow,purple

concole.log(colors2)// green,blue,yellow,purple

concole.log(colors3)// green,blue,yellow