JavaScript data type - array explanation

The Array object of JavaScript is a global object used to construct an Array, and an Array is a high-order object similar to a list.
Using regular expressions to match strings yields an array. This array contains the relevant information and matching results of this matching. RegExp.exec,String.match,String.replace will return such an array

Array properties

length

Gets the length of the array

prototype

You can add properties to all array objects through the prototype object of the array.

Create array
// Method 1
const arr = [1, 2, 3, 4]
// Method 2
const arr = new Array(1, 2, 3, 4)
// Method 3
const arr = new Array(4) // An array of length 4 is created. Each item of the array is undefined
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4 // Assign a value to each item of the array by index
// Method 4
let arr = []
arr.length = 4
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
console.log(arr) // Create an array of length 4 through length
// Method 5
const ofArr = Array.of(1, 2, 3)
console.log(ofArr)
Accessing arrays by index
const arr = [1, 2, 3, 4]
console.log(arr[0]) // 1

Array method

#######

Array.from()
  • Create a new, shallow copy of an array instance as an array or iteratable object
  • Parameter description
    • Object to convert
    • If the callback function is specified, each element of the new array executes the object's optional parameters
    • this in the callback function executes an optional parameter
const a = Array.from('foo', (x, y) => {
  console.log(x, y, this) // x represents each item of the object element, and y represents the subscript
  // f 0 {}
  // o 1 {}
  // o 2 {}
  return x
})
console.log(a)  // [ 'f', 'o', 'o' ]
Array.isArray(obj)

Determines whether the incoming object is an Array and returns a Boolean value

Array.of(ele)

Create a new array instance

const ofArr = Array.of(1, 2, 3)
console.log(ofArr)

Example method

forEach
  • Execute the given function once for each element of the array and traverse the array
  • The first parameter of foreach is a callback function. The three parameters of the callback function are the current element, the current index and the traversed array
  • The second argument to foreach is the this point in the callback function
  • Return undefined
arr.forEach((v,i,a) => {
  console.log(v,i,a)
})
map
  • The usage of map and forEach is similar, but the return values are different. Map returns a new array after the callback function is executed
  • If the callback does not have a return value, the default value is return undefined
const arr = [1, 2, 3, 4]
const a = arr.map(item => {
   console.log(item)
   return item
})
console.log(a) // [ 1, 2, 3, 4 ]

The same points of forEach and map
1. Loop through each item in the array
2. Each time the anonymous function is executed, three parameters are supported: item (each current item), index (index value), and arr (original array)
3. this in the anonymous function points to window
4. Only arrays can be traversed

Differences among forEach, map and for:
1. Using return in for can terminate the whole loop, but forEach and map only terminate the current loop
2. The map method will return a new array, but forEach returns undefined

push and pop
  • push(): add any number of parameters to the end of the array and return the length of the modified array
  • pop(): delete the last item at the end of the array and return the removed item
// add to
arr.push(8, 9, 19)
console.log(arr)
// delete
arr.pop()
shift() and unshift
  • shift(): deletes the first item of the array and returns the deleted element. If the array is empty, it returns undefined
  • unshift(): add any number of parameters to the beginning of the array and return the modified length
arr.unshift(1, 2, 3, 4)
arr.shift()
reverse
  • The position of the elements in the array is reversed and the array is returned. This method will change the original array.
  • Returns the inverted array
arr.reverse()
sort
  • Sort the elements of the array and return the sorted array
  • When the sort() method is called, it will use the toString() method for each item of the array, and then compare the obtained strings to determine how to sort
  • Parameter compareFunction(firstEl, secondEl)
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);
spllice
  • Realize the deletion, insertion and replacement of arrays
  • Returns an array of deleted elements. If there are no elements, an empty array is returned
  • parameter
    • Start: the position to start modification. If it exceeds the length of the array, add content from the end of the array. If it is a negative number, it means counting from the end of the array (starting from - 1, equivalent to length+start). If the absolute value of the negative number is greater than the length of the array, the start position is 0
    • The number of array elements to remove
    • The element to add to the array
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
// Delete the two from the penultimate one, that is, delete drum and sturgeon = = ["drum", "sturgeon"]
// myFish.splice(-2, 2) 

myFish.splice(-2, 0, 'aaa', 'bbb') // Starting from the penultimate, do not delete elements, only add = = "[]
console.log(myFish) // ["angel", "cloud", "AAA", "BBB", "drum", "sturgeon"] is added in front of the start position
concat
  • Merging two or more arrays does not change the original array, but returns a new array
var arr1 = [1]
var arr2 = [2]
var arr3 = [3]
arr1.concat(arr2, arr3) //  [1, 2, 3]
includes
  • Determine whether an array contains a specified value and return true or false
  • parameter
    • Value to judge
    • The index to start searching. If the index is negative, it will be calculated from the end (- 1) and then searched later. The default is 0
var arr = ['a', 'b', 'c'];
arr.includes('b', -1) // False because - 1 is equivalent to searching from c, false will be returned if b is not found
arr.includes('a', 3) // false exceeds the maximum index of the array
join
  • Converts all elements in the array to a string and returns
  • Parameter: used to split each element of the array
var arr = [1, 2, 3]
arr.join('+')
slice()
  • Intercepts the contents of the array and returns a new array composed of the specified start subscript and end subscript (excluding) in the array. The original array will not be changed
  • Parameter 1: represents the intercepted start subscript. If there is only one parameter, it represents the start subscript to the end
  • Parameter 2: end subscript of representative
  • Note: if the parameter is negative, the intercepted subscript is the length of the corresponding subscript + array
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
animals.slice(-1, -2) // [] returns an empty array if the end subscript is less than the start subscript
animals.slice(-3, -1) // ["camel", "duck"]
toString
  • Returns a string representing the specified array and its elements
const array1 = [1, 2, 'a', '1a'];
array1.toString() // "1,2,a,1a"
indexOf() and lastIndexOf()
  • indexOf find element index does not exist return - 1 return element index in array
  • lastIndexOf finds that the position of the last index in the array does not exist, and returns - 1
  • Parameter 1: the index of the searched element parameter 2
var arr = ['a', 'b', 'c', 'd', 'a']
arr.indexOf('a') // 0
arr.lastIndexOf('a') //4
every
  • Traverse the array, judge whether each element of the array meets the conditions, and return Boolean values
  • Parameter is a callback function
var arr = [2,4,6,10,15,21];
var f = arr.every(function(element, index, array){ // Current element subscript array
    return element > 10;
});

f // false
some
  • Traverse the array. If at least one element meets the conditions, it returns true; otherwise, it returns false.
  • Parameter is a callback function
var arr = [2,4,6,10,15,21];
var f = arr.some(function(element,index,array){ // Current element subscript array
    return element > 100
})
console.log(f) // false
filter
  • Filter - all the elements that meet the conditions in the array form a new array, and the return will not change the original array
  • Parameter is a callback function
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter((word, index, array) => word.length > 6);  // Current element subscript array
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
find
  • Returns the first value in the array that meets the condition. If the element is not found, it returns undefined
  • Parameter is a callback function
var arr = [2,4,6,10,15,21];
var f = arr.find(function(element, index, array){ // Current element subscript array
    return element > 10;
});
console.log(f) // 15 
findIndex
  • Returns the subscript of the first value in the array that meets the condition. If the element is not found, - 1 is returned
  • Parameter is a callback function
var arr = [2,4,6,10,15,21];
var f = arr.findIndex(function(element, index, array){ // Current element subscript array
    return element > 10;
})
console.log(f) // 4
copyWithin
  • Shallow copy a part of the array to another position in the same array and return it. It will not change the length of the original array, and the redundant part will be deleted automatically
  • parameter
    • If the index copied from target to location is negative, the index is equivalent to length + target
    • If the index copied from start is negative, the index is equivalent to length + start end, and the same is true
    • End the index that ends the copy does not include this element of end
const arr = [1, 2, 3, 4]
console.log(arr.copyWithin(2, 1, 2)) //  1, 2, 2, 4
reduce
  • Each element of the array executes the function in reduce, and the results are summarized into a single value and returned
  • Function parameters
    • The cumulative value returned by the last function call of the accumulator
    • currentValue the value currently being processed
    • Index current element index
    • arr array

Case: calculate the current sum by array

const reduceArr = [1, 2, 3, 4, 5, 6, 6]

const num = reduceArr.reduce((pV, cV, index, arr) => {
  console.log(pV, cV)
  return pV + cV
})
console.log(num ) // 27

Keywords: Javascript

Added by husslela03 on Mon, 17 Jan 2022 01:24:50 +0200