js array delete, add, modify

1: splice method in js

  splice(index,len,[item]) Note: This method changes the original array.

splice has 3 parameters, it can also be used to replace/delete/add one or several values ​​in the array

index: the starting subscript of the array len: the length of the replacement/deletion item: the value of the replacement, the item is empty for the deletion operation

Such as: arr = ['a','b','c','d']

Delete---- item is not set

arr.splice(1,1) //['a','c','d'] delete a value with a starting subscript of 1 and a length of 1, len is set to 1, if it is 0, the array is not Change

arr.splice(1,2) //['a','d'] delete a value whose starting subscript is 1 and length is 2, and len is set to 2

Replace ---- item is the replaced value

arr.splice(1,1,'ttt') //['a','ttt','c','d'] Replace the starting subscript with 1 and a value with length 1 of 'ttt', len set to 1

arr.splice(1,2,'ttt') //['a','ttt','d'] Replace the starting subscript with 1 and the two values ​​with length 2 as 'ttt', set by len 1

 

Add ---- len is set to 0, item is the added value

arr.splice(1,0,'ttt') //['a','ttt','b','c','d'] means adding an item 'ttt' at subscript 1

It seems that splice is the most convenient.

2: After delete delete deletes the elements in the array, it will set the value of the subscript to undefined, and the length of the array will not change

For example: delete arr[1] //['a', ,'c','d'] There are two commas in the middle, the length of the array is unchanged, and one item is undefined

There are several other custom methods, refer to here

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326725745&siteId=291194637