Some method cleanup of arrays (updating)

1 concat

The concat() method is used to merge two or more arrays. This method does not change an existing array, but returns a new one.

const arr1 = [1.2.3]
const arr2 = [4.5.6]
const arr3 = arr1.concat(arr2)
console.log(arr3)
Copy the code

2 findIndex

The findIndex() method returns the index of the first element in the array that meets the criteria, or -1 if none. It doesn’t change the original array.

const arr = [1.2.3.4.5.6.7.8]
let res = arr.findIndex(item= > item >= 7)
console.log(res)
let res2 = arr.findIndex(item= > item > 10)
console.log(res2)
Copy the code

3 every

Every () tests if all elements in an array are true, and returns true if not. Every does not change the array.

const arr1 = [1.2.3.4.5]
let res = arr1.every(item= > item > 10)
let res1 = arr1.every(item= > item >= 1)
console.log(res, res1)

const arr2 = []
console.log(arr2.every(item= > item > 1))
Copy the code

Note: If the array is an empty array, it returns true in any case.

4 join

The join() method concatenates all the elements in the array into a string and returns, if the array has only one item, that item is returned without a delimiter.

arr = [1.2.3.4.5]
arr1 = [null.1.undefined.1]
console.log(arr.join())
console.log(arr.join(' '))
console.log(arr.join(The '-'))
console.log(arr1.join(' '))
Copy the code

If an element is undefined or null, it is converted to an empty string.

5 reduce

The reduce() method accepts a function as the accumulator reduce argument

// Calculate the sum of arrays
arr = [1.2.3.4.5]
let res = arr.reduce((acc, item) = > acc += item)
console.log(res)
Copy the code

Return value: result of cumulative processing



The initial value is the sum of 10