JS — array method & higher order function

Time:2022-6-7

1、 Basic array usage

1. Create array method

(1) Use the new keyword

Let stu1 = new array ('zhang San ',' Li Si ',' Wang Wu ',' Zhao Liu ');

(2) Use brackets [], recommended

Let stu2 = ['Zhang San', 'Li Si', 'Wang Wu', 'Zhao Liu', 'Li Lei'];

(3) Use array of()

let stu3 = Array. Of ('zhang San ',' Li Si ',' Wang Wu ',' Zhao Liu ');

2. Length of array (property)

Length of array: the number of elements in the array. Use the length attribute

arr.length=3;         // You can assign values and change the length of the array; Generally not used

3. Array element subscript

(1) Subscript of elements in array starts from 0

The elements of the array can be accessed or modified through subscripts; Subscripts are written in square brackets.

console. log(arr[2]);    // Access the element with subscript 2 in the ARR array, that is, the third element
Fruit[2]= "lemon"// Modify and change the contents of the array

(2) Length of array

Length of array -1 = subscript of the last element

4. Quick empty array

(1) Directly create an empty array, recommended

   let arr = [];

(2) Empty array

   arr.length=0;

2、 Array method

1. Adding and deleting elements in an array

(1)unshift()

Adds an element to the front of the array and returns the new array length.

fruit. Unshift ('Orange ');

(2)push()

Adds an element to the last side of the array and returns the new array length

fruit. Push ('durian ');

(3)shift()

Delete the first element in the array; And return the deleted value

fruit2.shift();

(4)pop()

Delete the last element in the array; And return the deleted value

fruit2.pop();

2. Merge array concat

let arr4 = arr1. concat(arr2, arr3);  // Merge arr2 and arr3 into Arr1 to generate a new array arr4

3. Concatenate an array into a string join

Join () puts all the elements of the array into a string, separated by a delimiter.

//Set an empty string (without a connector) to connect the elements in the array into a string '20001128'
let str1 = date.join("");  
//Use the connector '-' to connect the elements in the array into a string '2000-11-28'
let str2 = date.join("-");

4、includes()

The include () method is used to determine whether an element is included in the array. It is case sensitive; Returns a Boolean value.

document. Write (fruit.includes ('watermelon ')// True, the fruit array contains watermelon elements
document. Write (fruit.includes ('strawberry ')// False, strawberry element is not included in fruit

5、indexOf()

Returns the position (subscript) of the first occurrence of a specified element in the array. If it is not found, it returns -1.

console.log(arr.indexOf('c'));

6、lastIndexOf()

Returns the last occurrence (subscript) of a specified element in an array.

console.log(arr.lastIndexOf('c'));

7. Intercept array slice()

(1) Grammar

Slice (start, end) intercepts the elements in the array; Do not manipulate the array itself (this method is also used for strings, but the array has no substring method.)
Returns an array of elements from start (inclusive) to end (exclusive), starting at 0.

let fru2=fruits. slice(1,3);   // Returns an array from subscript 1 (inclusive) to subscript 3 (exclusive)

(2) Rules

① If start is greater than or equal to end, an empty array is returned

let fru3=fruits. slice(3,1);   // Return empty array

② If there is only one parameter, it defaults to start, and returns from start (inclusive) to the end of the array

let fru4=fruits. slice(2);     // Returns an array from subscript 2 (inclusive) to the end of the array

③ If the value is negative, it will be treated as array length + negative number

let frus5=fruits. slice(-2);      // Returns the array length + (-2) to the end of the array
let fruits6=fruits. slice(-6);  // If the array length + negative or negative, the entire array is returned

8、splice()

Operation of the array itself, both delete, add and replace functions.
Format: splice (index, deleted quantity, added elements)
Index: from 0
Quantity deleted: optional; Integer indicating the number of array elements to be removed.
Added element: optional; One or more elements

fruits. splice(2,1);   //  Delete 1 element from position 2
fruits. splice(2,0);   //  The number of deleted elements is 0, and the array has no change
fruits. Splice (2,0, 'durian')// Without deleting the element, the element at position 2 becomes durian, and the original element moves backward
fruits. Splice (2,1, 'durian')// Delete the element at position 2 to become durian, and the other elements remain unchanged
fruits. Splice (2,3, 'durian')// Delete the 3 elements starting from position 2, and replace them with 1 durian element as a whole, and the remaining elements remain unchanged.

9. Reverse()

Reverse the position of the elements in the array, return the array, and operate on the array itself.

fruits.reverse();

10. Sort()

Sort by Unicode encoding of characters, from small to large. Manipulate the array itself.

fruits.sort();
//Sort X-Y from small to large, and Y-X from large to small
arr.sort(function(x,y){
      return x-y;
})

3、 Iterative method of array — higher order function

1、forEach()

The foreach () method is used to traverse the entire array. Return cannot be used in foreach.
Foreach (FN):fn is a callback function with two parameters (the parameter name is user-defined). The first parameter represents each item in the array, and the second parameter is the subscript.

        arr.forEach(function(item,index){
            console.log(item,index)
        })

2、filter()

Used to filter the original array and return a new array that meets the conditions.

let newScore = score. Filter (item = > item > 60) // find the

3、every()

Used to check whether all elements in the array meet the conditions; If one element makes the condition false, it will return false (all true ones will return true), and the remaining elements will not be detected.

let result1 = numbers. Every (item = > item < 10) // judge whether the numbers are all less than 10. If one of them is not satisfied, it is false

4、some()

Used to check whether there are elements that meet the conditions in the array; If one element makes the condition true, it will return true (if one element is true, it will be true), and the remaining elements will not be detected.

let result = score. Some ((item) = > item > 90) // judge whether there is a value greater than 90. As long as one of them is satisfied, it is true

5、find()

Used to find the first element in the array that meets the condition. If it is not found, it returns undefined.

let r1 = userlist.find(function(item){
            Return item = = = 'zhangsanfeng'
        })
        console. Log (R1) //'zhangsanfeng'

6、findIndex()

The index used to find the first element in the array that meets the condition. Return -1 if not found.

let r2 = userlist.findIndex(function(item){
            Return item = = = 'zhangsanfeng'
        })
        console.log(r2) // 1

7、reduce()

Loop through each item in the array to accumulate.
Syntax:arr.reduce(callback,[initialValue])
callback:The function that executes each value in the array contains four parameters: the initial value (or the return value of the previous callback function), the current element value, the current index, and the array that calls reduce.
initialValue:As the first parameter of the first call to callback.

Let r = arr.reduce ((a, b) = > a+b) // sum of all item values in arr
let sum = this. goodslist. Reduce ((a, b) = > A + b.price, 0) // count the sum of the price attribute of each item in goodslist, and set the initial value to 0

8、map()

Used to return all elements in the original array to a new array according to the conditions.

let arr2 = arr1.map(function(item){
    return item + 1;  // Each item in array Arr1 is added with 1 to form a new array arr2
 })