Js Several Methods of Deleting an Item or Items in an Array of Recommendation

  • 2021-07-06 09:41:47
  • OfStack

1. splice method in js

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

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

index: Array start subscript len: Length of replacement/deletion item: Value of replacement, item is empty for deletion operation

For example: arr = ['a', 'b', 'c', 'd']

Delete----item 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 remains unchanged

arr. splice (1, 2)//['a', 'd'] Delete 1 value with initial subscript 1 and length 2, len setting 2

Replace--item is the value of the replacement

arr. splice (1, 1, 'ttt')//['a', 'ttt', 'c', 'd'] Replaces the initial subscript of 1, the value of length 1 is' ttt ', and len sets 1

arr. splice (1, 2, 'ttt')//['a', 'ttt', 'd'] Replaces the initial subscript of 1, the two values of length 2 are 'ttt', and len sets 1

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

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

It seems that splice is the most convenient

2. After delete delete deletes the elements in the array, the value marked below will be set to undefined, and the length of the array will not change

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

There are several other customization methods, refer to here


Related articles: