preface

No foreword, just start, hahahahaha….

The method of traversing groups of numbers

forEach()

The forEach() method executes the given function once forEach item in the array in ascending order. grammar

Callback (callback(currentValue, index, array), thisArg)Copy the code
  • currentValue: Indicates the current value of the array
  • index: Index of the current entry in the array
  • arr: The array object itself
  • thisArg: This parameter is optional. When the callback function is executedcallbackWhen used asthisThe value of the.

Pay attention to

  • If you are usingArrow function expressionTo pass in the function parameters,thisArgArguments are ignored because the arrow function is lexically boundthisValue.
  • forEachDoesn’t directly change the object that calls it, but that object might becallbackThe function changes.
  • everyIt doesn’t change the array.

const arr = [2.3.4.1.44]

arr.forEach(val= >{
    console.log(` value is${val*2}`)})console.log(The original array is${arr}`);
/ / value of 4
/ / value is 6
/ / value is 8
/ / value of 2
/ / value is 88
// the original array is 2,3,4,1,44
Copy the code

reduce()

Reduce () accumulator of array elements, returning a combined result value. grammar

arr.reduce(callback(accumulator, currentValue, index, array), initialValue)
Copy the code
  • accumulator: accumulator, which defaults to the first value of the array element
  • currentValueThe current value:
  • index: The current element is optional
  • array: Arrays are optional
  • initialValue: Initial value This parameter is optional

Reduce takes two arguments, a callback function and an initial value. It has two values:

  1. When providing theinitialValueThe initial value, soaccumulatorThe value ofinitialValue , currentValueIs the first value in the array
  2. When not providedinitialValueThe initial value, soaccumulatorIs the first value in the array,currentValueIs the second value.

Pay attention to

  • If the array is empty and not suppliedinitialValueThe initial value is thrownTypeError .
  • If the array has one element and it is not providedinitialValueOr providedinitialValueIf the array is empty, then the unique value returned will not be executedcallbackCallback function.

sum

const arr = [1.2.3.4]

const sum = arr.reduce((accumulator, currentValue) = > accumulator + currentValue, 10)

console.log(sum) / / 20
Accumulator // Accumulator
// currentValue indicates the currentValue
// initialValue the cumulative initialValue is 10

//10 + 1 + 2 + 3 + 4


/ / # #
// The callback function is executed for the first time. There are two values on accumulator and currentValue.
// If initialValue is provided during the reduce() call, the accumulator value is initialValue and currentValue is the first value in the array.
// If initialValue is not provided, then Accumulator takes the first value in the array and currentValue takes the second value in the array.
Copy the code

To accumulate the values contained in the object array, you must provide an initial value for each item to pass through your function correctly.

const data = [
    {
        date: '2021-8-1'.income: 200
    },
    {
        date: '2021-8-2'.income: 400
    },
    {
        date: '2021-8-3'.income: 300},]console.log('Total revenue:${data.reduce( (pre,currentValue) => pre + currentValue.income,0)}`);
// Total revenue: 900
Copy the code

Turn a two-dimensional array into a one-bit array

const array = [[1.2], [3.4]]
console.log(array.reduce((a,b) = > a.concat(b)));
//[1, 2, 3, 4]
Copy the code

find()

Find () returns an element object or an element value that satisfies a specific condition, not the return undefined syntax

arr.find((element,index,array), thisArg)
Copy the code
  • element: Current element
  • index: Indicates the index of the current element
  • array: The array itself is optional
  • thisArg: used when executing a callbackthisIs optional
// Find the first object in the data that satisfies a specific condition
const data = [
    {
        name:'Joe'.article: 3
    },
    {
        name:'Lao wang'.article: 9
    },
    {
        name:'老李'.article: 10}]console.log(data.find(item= > item.article > 9 ));

// {name: 'Lao Li ', article: 10}
Copy the code

findIndex()

FindIndex () returns the index of the first element in the array that matches the criteria, or -1 if no. grammar

arr.findIndex((element,index,array), thisArg)
Copy the code
  • element: Current element
  • index: Indicates the index of the current element
  • array: The array itself is optional
  • thisArg: used when executing a callbackthisIs optional
const arr = [22.33.44.55]
console.log(arr.findIndex(val= > val > 33));    / / 2
console.log(arr.findIndex(val= > val > 99));    / / 1
Copy the code

key()

Key () returns a new Array Iterator containing the keys of each index in the Array.

grammar

keys()
Copy the code

Pay attention to

  • If the array is empty, it will be added to the traversal queue when the key is retrieved.
const inputModal = [
    {
        name:' '
    },
    {
        age:' '
    },
    {
        hobby:' '}]for(const key of inputModal.keys()){
    console.log(key)
}
/ / 0
/ / 1
/ / 2

const arr = [1.2.3]
for(const key of arr.keys()){
    console.log(key);
}
/ / 0
/ / 1
/ / 2
/ / 3


The object.keys () method returns an array of the self-enumerable properties of a given Object
// so object.keys (arr) = ['0', '1', '3']
for(const key of Object.keys(arr)){
    console.log(key);
}
/ / 0
/ / 1
/ / 3
Copy the code

values()

The values() method returns a new Array Iterator containing the value of each index of the Array.

grammar

arr.values()
Copy the code
const Color = ['red'.'yelloe'.'orange']

for(val of Color.values()){
    console.log(val);
}
// red
// yelloe
// orange
Copy the code

Returns a Boolean value

every()

Every is used to determine whether all elements in the array meet a certain condition and returns a Boolean syntax

Every (callback(currentValue, index, array), thisArg)Copy the code
  • currentValue: The current value of the array must be
  • index: Index of the current array item This parameter is optional
  • arrThe array object itself is optional
  • thisArg: This parameter is optional. When the callback function is executedcallbackWhen used asthisThe value of the optional

Pay attention to

  • It is returned when all elements meet the criteriatrue
  • everyIt doesn’t change the array.
  • If I pass in an empty array, I’ll return it anyway, righttrue.
const arr = [2.3.4.1.44]

console.log(arr.every(val= >  val > 0 ));   //true

console.log(arr.every(val= > { val > 2 })) //false
Copy the code

some()

Some () is used to determine whether the elements of an array meet a condition, and returns true if one of them does.

grammar

Some (callback(currentValue, index, array), thisArg)Copy the code
  • currentValue: The current value of the array must be
  • index: Index of the current array item This parameter is optional
  • arrThe array object itself is optional
  • thisArg: This parameter is optional. When the callback function is executedcallbackWhen used asthisThe value of the optional

Pay attention to

  • some()It doesn’t change the array when it’s called.
  • If you test with an empty array, in any case it returns 0false.
  • some()During the traversal, the element scope is determined, and elements added during the traversal are not added to the traversal sequence.
const arr = [2.3.4.1.44]

console.log(arr.some(val= > val > 2))  //true
console.log([].some(val= > val > 2 )); //false

const newList = [11.22.33.44]
console.log(newList.some(val= > {
    newList.push(55)
    newList.push(66)
    val > 55
}));   //false
Copy the code

Form a new array without changing the original array

filter()

Filter () is used to iterate through the original array and filter the array elements that meet the conditions to form a new array element. grammar

Some (callback(currentValue, index, array), thisArg)Copy the code
  • currentValue: The current value of the array must be
  • index: Index of the current array item This parameter is optional
  • arrThe array object itself is optional
  • thisArg: This parameter is optional. When the callback function is executedcallbackWhen used asthisThe value of the optional

Pay attention to

  • filterIt doesn’t change the old array, it returns the new filtered array.
  • filter()During the traversal, the element scope is determined, and elements added during the traversal are not added to the traversal sequence.
const arr = [11.22.33.44.55.66]
console.log(arr.filter(val= > val > 44 ))
console.log(The original array is${arr}`);

// [55, 66]
// the original array is 11,22,33,44,55,66
Copy the code

map()

Map () creates a new array, and the result is the result of calling one of the provided functions for each element in the array.

grammar

Arr. map(callback(currentValue, index, array), thisArg)Copy the code
  • currentValue: The current value of the array must be
  • index: Index of the current array item This parameter is optional
  • arrThe array object itself is optional
  • thisArg: This parameter is optional. When the callback function is executedcallbackWhen used asthisThe value of the optional

Pay attention to

  • map Do not modify the original array itself that called it
  • map()During the traversal, the element scope is determined, and elements added during the traversal are not added to the traversal sequence.
const arr = [1.2.3.4]
console.log(arr.map(val= > val*3 ))  // [3, 6, 9, 12]
console.log(arr)  // [1, 2, 3, 4]
Copy the code

An array of CRUD

Change the array method

reverse()

The reverse() method reverses the positions of the elements in the array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method changes the array.

const arr = [1.2.3]

console.log(arr.reverse(11.22.33))  //[3, 2, 1]
Copy the code

sort()

The sort() method uses the in-place algorithm to sort and return an array. The default sort order is to convert elements to strings and then compare them to a sequence of UTF-16 code unit values

An in-place algorithm is an algorithm that uses auxiliary data structures to transform the input. However, it allows for a small amount of additional storage space for auxiliary variables. When an algorithm runs, the input is often overwritten by the output. The in-place algorithm updates the input sequence only by replacing or swapping elements.

const arr = [23.11.33.44.1]

console.log(arr.sort())  //[1, 11, 23, 33, 44]


const arr = [23.11.33.44.1000000000]

console.log(arr.sort())  
// [1000000000, 11, 23, 33, 44]
Copy the code

Remove elements

shift()

The shift() method removes the first element from the array and returns its value. This method changes the length of the array.

grammar

arr.shift()
Copy the code

Pay attention to

  • The element removed from the array; Returns if the array is emptyundefined
const data = [
    {
        id:1.name:'front end'
    },
    {
        id:2.name:'back-end'
    },
    {
        id:3.name:'Mobile'
    },
    {
        id:4.name:'Embedded Development'},]const deleObj = data.shift()



console.log('============== deleted element ======================');
console.log(data);
console.log('================= deleted element ===================');


console.log('=============== Deleted element =====================');
console.log(deleObj);
console.log('================ Deleted element ====================');

// ============== The deleted element ======================
/ / /
// {id: 2, name: 'backend'},
// {id: 3, name: 'mobile'},
// {id: 4, name: 'embedded development'}
/ /]
// ================= The deleted element ===================

  
// =============== The deleted element =====================
// {id: 1, name: 'front'}
// ================ The deleted element ====================
Copy the code

pop()

The pop() method removes the last element from the array and returns its value. This method changes the length of the array.

The usage is similar to shift.

grammar

arr.pop()
Copy the code

Pay attention to

  • The element removed from the array; Returns if the array is emptyundefined
const data = [
    {
        id:1.name:'front end'
    },
    {
        id:2.name:'back-end'
    },
    {
        id:3.name:'Mobile'
    },
    {
        id:4.name:'Embedded Development'},]const deleObj = data.pop()




console.log(data);
/ / /
// {id: 1, name: 'front'},
// {id: 2, name: 'backend'},
// {id: 3, name: 'mobile'}
// ]
console.log(deleObj);
// {id: 4, name: 'embedded development'}
Copy the code

splice()

The splice() method modifies the array by removing or replacing existing elements or adding new ones in place, and returns the modified contents as an array. This method changes the array.

grammar

array.splice(start,deleteCount, [item1,item2....] )Copy the code
  • start: Indicates the starting index
  • deleteCount: This parameter is optional
  • [item1, item2...].; Add and replace elements from the starting index, optional

Pay attention to

  • An array of deleted elements. If only one element is removed, the array containing only one element is returned. If no element is deleted, an empty array is returned.
  • If only the starting index position is passed, all element objects after the index are deleted
const data = [
    {
        id:1.name:'front end'
    },
    {
        id:2.name:'back-end'
    },
    {
        id:3.name:'Mobile'
    },
    {
        id:4.name:'Embedded Development'
    },
]
data.splice(1)
console.log(data)
// [{id: 1, name: 'front'}]
Copy the code

Starting with index 2, remove 1 array element object and add two array element objects

const data = [
    {
        id:1.name:'front end'
    },
    {
        id:2.name:'back-end'
    },
    {
        id:3.name:'Mobile'
    },
    {
        id:4.name:'Embedded Development'
    },
]


data.splice(2.1. [{id:5.name:'Artificial intelligence'}, {id:6.name:'Big Data Development'}])

console.log(data);
/ / /
// {id: 1, name: 'front'},
// {id: 2, name: 'backend'},
// {id: 5, name: 'ai'},
// {id: 6, name: 'big data development'},
// {id: 4, name: 'embedded development'}
// ]
Copy the code

Add elements

splice()

It has been described above

push()

The push() method adds one or more elements to the end of the array and returns the new length of the array.

grammar

arr.push(element1, ... , elementN)Copy the code
const data = [
    {
        id:1.name:'front end'
    },
    {
        id:2.name:'back-end'},]console.log(data.push({id:3.name:'Mobile'}))  / / 3
Copy the code

Merge array

const data = [
    {
        id:1.name:'front end'
    },
    {
        id:2.name:'back-end'},]var obj = [
    {
        id:4.name:'Embedded Development'},]Data.push ({id:4,name:' embedded development '});
Array.prototype.push.apply(data, obj);

console.log(data); [{id: 1.name: 'front end' },
  { id: 2.name: 'back-end' },
  { id: 4.name: 'Embedded Development'}]Copy the code

unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

const arr = [1.2.3]

console.log(arr.unshift(11.22.33))  / / 6
console.log(arr)  //[11, 22, 33, 1, 2, 3]
Copy the code

Do not change the array element method

indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if none exists.

grammar

indexOf(searchElement)
indexOf(searchElement, fromIndex)
Copy the code
  • SearchElement: The element to look for

  • FromIndex: The first index of the element that appears in the search by the specified index is optional

    • If the index is greater than or equal to the length of the array, return -1
    • If the index value supplied is negative, it is treated as an offset from the end of the array
    • If the supplied index is negative, the array is still searched from front to back
    • If the supplied index is 0, the entire array is searched.
    • Default: 0 (search the entire array).
const arr = [1.1.2.3.4.5.4.4.6]

console.log(arr.indexOf(3));  / / 3
console.log(arr.indexOf(9));  / / 1

console.log(arr.indexOf(3.4)); / / 1
// Look for 3 from an element whose index is 4, and return -1
Copy the code

Array to heavy

Create a new empty array, use indexOf to determine if the empty array has an element for the first time,

  • If not, return [< 0],pushTo the empty array.
const newArr = []
arr.forEach(val= > {
    if(newArr.indexOf(val) < 0){
       newArr.push(val)
    }
})
console.log(newArr);
// [1, 2, 3, 4, 5, 6]
Copy the code

lastIndexOf()

LastIndexOf () finds the index of the last occurrence of an element in the array, and returns -1 if not found.

Returns -1 if it does not exist. Look forward from the back of the array, starting at fromIndex.

grammar

arr.lastIndexOf(searchElement, fromIndex)
Copy the code
  • SearchElement: The element to look for

  • FromIndex: Searches for the first index of the specified element that appears by the specified index. optional

    • Lookup backward from the specified index location
    • The default is the length of the array minus1(arr.length - 1), i.e. the entire array is searched.
    • If the value is greater than or equal to the length of the array, the entire array is looked up.
    • If it is negative, the array will still be looked up backwards.
    • If the value is negative and its absolute value is greater than the array length, the method returns -1, that is, the array is not looked up.

Pay attention to

  • lastIndexOfUsing theStrictly equal= = =searchElementAnd the elements in the array.
const arr = [1.1.2.3.4.5.4.4.6]

console.log(arr.lastIndexOf(4)); / / 7

console.log(arr.lastIndexOf(4.11));  
//7 specifies that the search index is greater than the length of the array

console.log(arr.lastIndexOf(4, -33));
// If the index is negative and the absolute value is greater than the length of the array, return -1

console.log(arr.lastIndexOf(4, -5));
//4 If the specified index is negative and the absolute value is less than the array length, the search will proceed forward
Copy the code

inCludes()

The includes() method determines whether an array contains a specified value, returning true if it does, or false otherwise.

grammar

arr.includes(searchElement, fromIndex)
Copy the code
  • SearchElement: The element to look for

    Search is case sensitive

  • FromIndex: Searches for the first index of the specified element that appears by the specified index. optional

    • Lookup from the specified index
    • If the value is negative, then in ascending orderarray.length + fromIndexThe index began to search
    • iffromIndexIs greater than or equal to the length of the arrayfalseAnd the array will not be searched.
    • The default is 0
const arr = [1.1.2.3.4.5.4.4.6]

console.log(arr.includes(4)); //true

console.log(arr.includes(4.66)); //false

console.log(arr.includes(1, -1)); //false
Copy the code

concat()

The concat() method is used to merge two or more arrays.

var new_array = old_array.concat([arr1][arr2])
Copy the code

Pay attention to

  • The concat method does not change this or any array provided as an argument, but instead returns a shallow copy that contains a copy of the same elements combined with the original array

    • Object references (not actual objects) :concatCopy the object reference into the new array. Both the original array and the new array refer to the same object. That is, if the referenced object is modified, the change is visible to both the new array and the original array. This includes elements that are also array parameters.
    • Data types such as string, number, and Boolean (notString.NumberandBoolean) Object:concatCopies the string and number values into the new array.
let arr1 = [1.2.3]
let arr2 = [4.5.6]
let arr3 = [[1.2], [3.4]]
console.log(arr1.concat(arr2));
//[1, 2, 3, 4, 5, 6]

// Nested merge
console.log(arr1.concat(arr2).concat(arr3));
// [1, 2, 3, 4, 5, 6, [1, 2], [3, 4]]


let obj1 = [{a:1}, {b:2}]
let obj2 = [{c:3}, {d:4}]
let obj3 = obj1.concat(obj2)  
console.log(obj3); 
//[ { a: 1 }, { b: 2 }, { c: 3 }, { d: 4 } ]


obj1[0].a = 4  // Changing the value of the obj[0] object directly affects the merged array because it is a shallow copy
console.log(obj3); 
//[ { a: 4 }, { b: 2 }, { c: 3 }, { d: 4 } ]
Copy the code

toString()

ToString () returns a string representing the specified array and its elements.

It is called automatically when an array is treated as a text value or string concatenation is performedtoStringMethods.

For array objects, the toString method concatenates the array and returns a string containing each array element separated by a comma.

grammar

arr.toString()
Copy the code
const arr = [1.2.3]

console.log(arr.toString());  / / 1, 2, 3
Copy the code

join()

The join() method returns a string by concatenating array elements separated by commas or the specified delimiter string.

If the array has only one item, the item is returned without a delimiter.

grammar

join()
join(separator)
Copy the code
  • separator: The specified split character is optional
const arr = ['2021'.'08'.'08']

console.log(arr.join());     / / 2021,08,08
console.log(arr.join(The '-'));  / / 2021-08-08
console.log(arr.join('/'));  / / 2021/08/08
Copy the code

slice()

The slice() method returns a new array object that is a shallow copy of the original array determined by begin and end (including begin but not end). The original array will not be changed. grammar

arr.slice(begin, end)
Copy the code
  • Begin: Indicates the start index for interception. This parameter is optional

    • The default starts at 0
    • ifbeginIs negative, then the interception starts with the absolute value starting at the end of the arrayslice(-2)The second element at the end
    • ifbeginIf the index range of the original array is exceeded, an empty array is returned.
  • End: The end index to specify the interception is optional

    • ifendIs omitted, thensliceIt’s going to go all the way to the end of the array.
    • ifendIs greater than the length of the array,sliceIt’s going to go all the way to the end of the array.
    • ifendIs a negative number, it indicates the number of elements in the original array to end the extraction.
const arr = [11.22.33.44.55.66.77.88]
console.log(arr.slice(1.4));
// Array elements with indexes 1-3 should be returned
// [22, 33, 44]

console.log(arr.slice(-4.2))  / / []

console.log(arr.slice(-4));   //[55, 66, 77, 88]

console.log(arr.slice(0, -1));
/ / /
// 11, 22, 33, 44,
/ / 55, 66, 77
/ /]
Copy the code