Array objects

  • Array objects are a special kind of object

  • In JS, there is no real array, just using objects to simulate arrays (i.e. pseudo-arrays).

JS array is not a typical array

Typical arrays:

  • Elements of the same data type
  • Use continuous memory storage
  • Gets the element by numeric subscript

JS uses objects to simulate arrays

  • Elements can have different data types
  • Memory is not necessarily contiguous (objects are stored randomly)
  • You can’t subscript by numbers, you can subscript by strings
  • This means that an array can have any key, such as:Let arr = [1, 2, 3] | arr['xxx']= 1

Create an array

  • new
let arr = [1.2.3]
let arr = new Array(1.2.3)
let arr = new Array(3)
Copy the code
  • conversion
let arr = '1, 2, 3'.split(', ') // Create an array from a string, separated by a, and
let arr = '123'.split(' ') // Separate the characters with an empty string
Array.from('123')  // To try to make an array out of something that is not an array, you must satisfy two conditions: the object has '0', '1', '2'... The subscript; Has length attribute
Copy the code

  • Pseudo array

let divList = document.querySelectorAll('div')

The stereotype chain of the pseudo-array does not have the stereotype of the array, such as push, pop, etc. An array without an array shared property is a pseudo-array. Pseudo-arrays have no real purpose. Every time we encounter a pseudo-array, we use array. from to convert it to an Array.

Create an array (continued)

  • You merge two arrays, you get a new array, you don’t change the original array

arr1.concat(arr2)

  • Intercepts part of an array
arr1.slice(1) // Cut from the second element without changing the original data
arr1.slice(0) // Often used to copy arrays
Copy the code

Note: JS provides shallow copies

Three, array add, delete, modify and check

Delete elements

  • Delet way
let arr = ['a'.'b'.'c']
delete arr['0'] // Delete the first element
arr //[empty,'b','c'] The size of the array remains unchanged
delate arr[1]
delate arr[2] [empty*3] [empty*3] [empty*3] [empty*3] [empty*3
Copy the code

The above method is more suitable for deleting objects and is not recommended for arrays.

  • Change the length deletion method
let arr = [1.2.3.4.5];
arr.length = 2
arr // array elements after [1,2] will be deleted without error, which is prone to bugs in practice
Copy the code

!!!!! Note: Do not change the length arbitrarily, the above two methods: delete/change length, are not recommended

Recommended ways to delete elements

  • Remove the header element
arr.shift() // The arr is modified and returns the deleted element
Copy the code
  • Remove the trailing element
arr.pop()  // The arr is modified and returns the deleted element
Copy the code
  • Delete the middle element
arr.splice(index,1)  // Delete 1 element from index

arr.splice(index,1.'x')  // add 'x' to delete position

arr.splice(index,1.'x'.'y') // Add 'x','y' to delete position
Copy the code

View all elements

  • View all property names
let arr = [1.2.3.4.5]; arr.x ='xxx'

Object.keys(arr)

for(let key in arr){console.log(`${key}:${arr[key]}`)}
Copy the code

The abovefor inMethods are only suitable for viewing objects, not arrays, and are not recommended.

recommendedfor letCheck the method

  • View numeric (string) property names and values

Method one: the for loop

for(let i = 0; i < arr.lenght; i++){
   console.log(`${i}: ${arr[i]}`)}// When accessing an array, specify that the index must grow from 0 to length-1
Copy the code

Method 2: Use functions from the prototype such as forEach/map

arr.forEach(function(item, index){
  console.log(`${index}: ${item}`)})Copy the code

The difference between the two approaches:

1. The for loop has break and continue, and forEach is not supported, so it executes all at once.

2. The for loop is the keyword and has no function scope, only block-level scope. ForEach is a function with scope.

How to understand forEach

function forEach(array, fn){
  for(let i = 0; i<array.length; i++){
    fn(arry[i], i, array)
  }
}
Copy the code

ForEach uses for to access each item in the array;

Call fn(arry[I], I,array) for each item, get each item in the array and pass each item to fn as an argument to fn.

Viewing individual properties

  • The subscript method
let arr = [111.222.333]
arr[0]  / / 111
Copy the code
  • The index of crossing the line
arr[arr.length] === undefined
arr[-1= = =undefined
// Any subscript that does not exist to read is undefined
Copy the code

For example,

let arr = [1.2.3.4.5.6.7]
for(let i = 0; i<= arr.lenght; i++){  //<=length is not allowed. The value of length cannot be queried. The value can only be length-1
    console.log(arr[i].tostring())
}
Copy the code

Cannot read property 'toString' of underfinedIt means you read itundefinedthetoStringProperty doesn’t meantoStringisundefined.x.toString()Among themxIf it isundefinedThis error will appear.

Viewing a single property (continued)

  • Finds whether an element is in an array
arr.indexOf(item) // There is a return index, otherwise -1 is returned
Copy the code
  • Use conditions to find elements
arr.find(item= > item %2= = =0)  // Find the first even number
Copy the code

But find returns only the element, not the index. Instead, you can use findIndex to return the index of the corresponding element.

  • Find the index of an element using a condition
arr.findIndex(item= > item%2= = =0) // Find the index with the first even number
Copy the code

Increments an element in an array

  • Add elements at the end
arr.push(newItem)  // Modify arr to return the new length
arr.push(item1,item2) // Change arR to return the new length
Copy the code
  • Add elements to the header
arr.unshift(newItem)  // Modify arr to return the new length
arr.unshift(item1,item2) // Change arR to return the new length
Copy the code
  • Add elements in the middle
arr.splice(index,0.'x') // Insert 'x' at index
arr.splice(index,0.'x'.'y')
Copy the code

Modify elements in the data

  • Substitution method
let arr = [11.22.44]
arr[2] = 33  // Replace '33' where '2' is subscript
Copy the code
  • Reverse order
arr.reverse()  // Modify the original array
Copy the code

Extension: “How to Reverse the Order of Strings”

Strings are not reverse. Strings need to be split into arrays, then arrays need to be reversed, and finally strings need to be synthesized.

  • Custom order
arr.sort((a,b) = > a-b)
Copy the code

If compareFunction(a, b) is less than 0, then a is arranged before B;

If compareFunction(a, b) is equal to 0, the relative positions of a and b remain the same.

If compareFunction(a, b) is greater than 0, b will be arranged before A.

If compareFunction is not set, JS defaults to the smaller value first and the larger value last, eg: 1,2,3. But in fact, JS does not know who is small and who is big, so it needs to set 1, -1, 0 to let JS judge.

For example,

An array of transformation

  • map

N variable n

  • filter

N less

  • reduce (Can replace map and filter, but not very friendly to new people, more practice)

N become 1

Code practice