Common Addition Deletion Modification and Explanation of Other Attributes of JavaScript Array

  • 2021-08-31 06:59:30
  • OfStack

Addition, deletion and modification of array

Insertion of array

push () tail insert


var arr2 = [1, 2, 3]
 arr2.push(4, 5, 6)
 console.log(arr2) //[1,2,3,4,5,6]

unshift () Head Insertion


var arr3 = [1, 2, 3]
arr3.unshift(4, 5, 6)
  console.log(arr3) //[4, 5, 6, 1, 2, 3]

splcie is inserted or deleted in any position

arr. splice (n, m, x) deletes the elements of m from the index n, puts the newly added element X before the index n, (Equivalent to deleting an element at any location and inserting it)

  var arr4 = [1, 2, 3]
  arr4.splice(1, 1, 888, 999)
  console.log(arr4) // Index 1 Start, delete 1 Elements, and then add 888 , 999
arr. splice (n, 0, x) deletes 0 elements from the index n, places the newly added element x before the index n, (Equal to insert before any position)

  var arr5 = [1, 2, 3]
  arr5.splice(1, 0, 888, 999)
  console.log(arr5) // Index 1 Start, delete 0 Elements, and then in the index 1 Pre-increase 888 , 999
arr. splice (n, m) deletes m elements from the index n, returns the deleted contents as a new array, changes the original array, (Equivalent to deleting elements)

 var arr6 = [1, 2, 3]
  arr6.splice(1, 1)
  console.log(arr6) // Index 1 Start, delete 1 Elements 

Deletion of array

pop () deletes the last entry of the array


var arr7 = [1, 2, 3]
  arr7.pop()
  console.log(arr7)

shift () deletes the first item of the array and returns the deleted item. The original array changes


var arr8 = [1, 2, 3]
  arr8.shift()
  console.log(arr8)

Query of array

The query uses indexOf (). If there is an index value returned, there is no return-1


 var arr9 = [4, 5, 6, 's']
  console.log(arr9.indexOf('s')) //3

Others

Array Custom Connection Symbol join ()


var arr10 = [4, 5, 6, 's']
  console.log(arr10.join("-")) //4-5-6-s

Array combining concat ()


 - var arr11 = [1, 2, 3]
  var arr11 = arr11.concat(7, 8, 9)
  console.log(arr11) //7 , 8 , 9 Merge into arr11
  var arr12 = [4, 5, 6]
  var arr13 = [7, 8, 9]
  console.log(arr12.concat(arr13)) //arr13 Merge into arr12

Arrangement and Sorting of Arrays

reverse () Reverses Array


var arr3 = [1, 2, 3]
arr3.unshift(4, 5, 6)
  console.log(arr3) //[4, 5, 6, 1, 2, 3]
0

sort can sort from big to small or from small to large, but sort can only sort numbers within 10


var arr3 = [1, 2, 3]
arr3.unshift(4, 5, 6)
  console.log(arr3) //[4, 5, 6, 1, 2, 3]
1

Any number is sorted from small to large


var arr3 = [1, 2, 3]
arr3.unshift(4, 5, 6)
  console.log(arr3) //[4, 5, 6, 1, 2, 3]
2

Summarize


Related articles: