Summary of commonly used array methods in JavaScript

forEach() function

The forEach() function is a method provided by JavaScript arrays for traversing the array. It takes a callback function as an argument and calls the callback function in turn for each element in the array.

The syntax of the forEach() function is as follows:

array.forEach(callback(currentValue, index, array), thisArg)

Parameter Description:

  • callback: Required, indicating the callback function executed on each array element.
  • currentValue: Required, indicating the value of the currently traversed element.
  • index: optional, indicating the index of the currently traversed element.
  • array: Optional, indicating the array being traversed.
  • thisArg: Optional, indicating the this value used when executing the callback function.

In the callback function, we can perform any operation on each array element, such as printing the value of the element, modifying the value of the element, etc.
For example, the following piece of code uses the forEach() function to iterate through an array:

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(number, index) {
  console.log(`第 ${index} 个元素的值是:${number}`);
});

Run the program, the console output is as follows:

第 0 个元素的值是:1
第 1 个元素的值是:2
第 2 个元素的值是:3
第 3 个元素的值是:4
第 4 个元素的值是:5

Note that when traversing the array, the forEach() function will call the callback functions in sequence according to the order of the array, but the execution order of the callback functions is not guaranteed. If you need to perform operations in a specific order, you can use other methods, such as for loops.

map() function

The map() function is used to perform the specified operation on each element in the array and return a new array whose elements are obtained by operating on each element of the original array.

The map() function is used when we want to perform the same operation on each element in the array and return a new array. It traverses each element in the array, and passes each element to the callback function for processing, and finally returns the processed results as a new array.

The map() function accepts a callback function as a parameter, and the callback function can accept three parameters: the value of the current element, the index of the current element, and the array itself. The callback function performs an operation on each element and adds the returned value to the new array.

The syntax of the map() function is as follows:

array.map(callback(currentValue[, index[, array]])[, thisArg])

Parameter Description:

  • callback: A function to process each element. Accepts three parameters:
    • currentValue: The element currently being processed.
    • index(optional): The index of the current element.
    • array(optional): the original array.
  • thisArg(Optional): The this value used when executing the callback function.

Here is the code that converts each element in the array to uppercase using the map() function:

const fruits = ['apple', 'banana', 'orange'];

const upperCaseFruits = fruits.map((fruit) => fruit.toUpperCase());

console.log(upperCaseFruits); // 输出: ['APPLE', 'BANANA', 'ORANGE']

filter() function

The filter() function is used to filter the elements in the array that meet the specified conditions and return a new array. This method does not mutate the original array, but creates a new array based on the condition.

The filter() function accepts a callback function as a parameter, and the callback function is used to define the filter condition. The callback function can accept three parameters: the current element, the current index, and the original array. It should return a boolean value, true means the element meets the condition and will be included in the new array, false means the element does not meet the condition and will be filtered out.

filter()The syntax of the function is as follows:

array.filter(callback(element[, index[, array]])[, thisArg])

where arrayis the array to be filtered and callbackis a callback function that is called on each array element. The callback function accepts three parameters: elementthe array element currently being processed, indexthe index of the current element (optional), arrayand the array being processed (optional).

The callback function returns a boolean value, if it returns true, it means that the current element meets the conditions and will be included in the new array. If returned false, it means that the current element does not meet the conditions and will be filtered out.

thisArgParameters are optional and are used to specify thisvalues ​​in the callback function.

In the following code we use the filter() function to filter array elements:

const numbers = [1, 2, 3, 4, 5, 6];

// 使用filter()函数筛选出所有大于3的元素
const filteredNumbers = numbers.filter(function(number) {
    
    
  return number > 3;
});

console.log(filteredNumbers); // 输出 [4, 5, 6]

Instead of using anonymous functions as callback functions, we can also use arrow functions to simplify the code.

const numbers = [1, 2, 3, 4, 5, 6];

// 使用箭头函数筛选出所有大于3的元素
const filteredNumbers = numbers.filter(number => number > 3);

console.log(filteredNumbers); // 输出 [4, 5, 6]

reduce() function

The reduce() function is a powerful method of JavaScript arrays, which can perform operations such as accumulation, multiplication, and string concatenation on elements in the array. It receives a callback function as an argument, and can be passed an initial value. The callback function accepts four parameters: accumulator, current value, current index and original array.

The syntax of the reduce() function is as follows:
array.reduce(callback[, initialValue])

Among them, callback is a callback function, which can accept four parameters: accumulator, currentValue, currentIndex and array. initialValue is optional and is used to set the initial value.

The following piece of code uses the reduce() function to accumulate an array:

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, currentValue) => {
    
    
  return accumulator + currentValue;
}, 0);

console.log(sum); // 输出:15

In addition to accumulation, the reduce() function can also be used for operations such as multiplication and string concatenation.

const numbers = [1, 2, 3, 4, 5];

const product = numbers.reduce((accumulator, currentValue) => {
    
    
  return accumulator * currentValue;
}, 1);

console.log(product); // 输出:120

find() function

find()The function iterates through each element in the array and returns the first element that satisfies the given condition. Returns if no element is found that satisfies the condition undefined. find()JavaScript functions can be used when we want to find the first element in an array that satisfies a certain condition .

find()The syntax of the function is as follows:

array.find(callback(element[, index[, array]])[, thisArg])

Parameter Description:

  • array: The array in which to find the element.
  • callback: callback function, receiving three parameters:
    • element: The array element currently being processed.
    • index(optional): The index of the element currently being processed.
    • array(optional): find()An array of functions to call.
  • thisArg(Optional): An object to use as a keyword when executing the callback function this.

find()The working principle of the function is that it traverses sequentially from the first element of the array, and when it finds the first element that satisfies the condition, it stops traversing and returns that element. Returns if no element is found that satisfies the condition undefined.

The following code uses find()a function to find the first element greater than 10 in an array:

const numbers = [5, 8, 12, 3, 15, 7];
const foundNumber = numbers.find(function(element) {
    
    
  return element > 10;
});

console.log(foundNumber); // 输出:12

Note that the condition in the callback function can be any JavaScript expression. Depending on your needs, you can define your own conditions based on attributes, indexes, or other conditions of the element.

some() and every()

some()The every()sum function is a method for judging whether the elements in the array meet certain conditions.

some()The function is used to determine whether there is an element in the array that satisfies the given condition. It traverses each element in the array, and returns when any element meets the condition true. Returns if no element is found that satisfies the condition false.

some()The syntax of the function is as follows:

array.some(callback(element[, index[, array]])[, thisArg])

Parameter Description:

  • array: The array to check for elements in.
  • callback: callback function, receiving three parameters:
    • element: The array element currently being processed.
    • index(optional): The index of the element currently being processed.
    • array(optional): some()An array of functions to call.
  • thisArg(Optional): An object to use as a keyword when executing the callback function this.

some()The working principle of the function is that it traverses sequentially from the first element of the array, and when it finds an element that satisfies the condition, it stops traversing and returns true. Returns if none of the elements in the array satisfy the condition false.

The following code uses some()a function to determine whether there are elements greater than 10 in the array:

const numbers = [5, 8, 12, 3, 15, 7];
const hasGreaterThan10 = numbers.some(function(element) {
    
    
  return element > 10;
});

console.log(hasGreaterThan10); // 输出:true

every()The function is used to judge whether all the elements in the array meet the given condition. It iterates through each element in the array and returns when all elements meet the condition true. Returns if there is an element that does not satisfy the condition false.

every()The syntax of the function is as follows:

array.every(function(currentValue, index, array) {
    
    
    // 执行某些操作
}, thisArg);

Parameter Description:

  • function(currentValue, index, array): Required. This is a callback function that specifies the action to be performed on each element. It receives three parameters:

    • currentValue: The value of the current element.
    • index: The index of the current element.
    • array: every()Array of calling functions.
  • thisArg(Optional): Specify a value to use in the callback function this.

every()The function will call the callback function once for each element in the array, and if the callback function returns for all elements true, every()the function will eventually return true. If the callback function returns for any element false, every()the function returns immediately falsewithout checking the remaining elements.

The following code uses every()a function to determine whether all elements in an array are less than 20:

const numbers = [5, 8, 12, 3, 15, 7];
const allLessThan20 = numbers.every(function(element) {
    
    
  return element < 20;
});

console.log(allLessThan20); // 输出:true

sort() function

sort()Functions are used to sort array elements. It rearranges the array elements in the default sort order and returns the sorted array.

sort()The function sorts the elements of the array by converting them to strings and then comparing the Unicode encoded values ​​of the strings. By default, sort()the function converts the elements to strings for sorting, even if the elements in the array are numeric.

sort()The syntax of the function is as follows:

array.sort(compareFunction)

Parameter Description:

compareFunctionis an optional callback function that defines the collation. It receives two arguments (often called aand b), representing the two elements to be compared. compareFunctionNeeds to return a negative number, zero or positive number, depending on the arelative border of the sum.

If it returns a negative number, it means ait should be bbefore; if it returns zero, it means the sum ais bequal; if it returns a positive number, it means ait should be bafter.

The following code uses sort()a function to sort an array:

// 数字数组排序
const numbers = [5, 1, 3, 2, 4];
numbers.sort();
console.log(numbers); // 输出:[1, 2, 3, 4, 5]

// 字符串数组排序
const fruits = ['banana', 'apple', 'orange', 'grape'];
fruits.sort();
console.log(fruits); // 输出:['apple', 'banana', 'grape', 'orange']

// 对象数组排序
const persons = [
  {
    
     name: 'Alice', age: 25 },
  {
    
     name: 'Bob', age: 20 },
  {
    
     name: 'Charlie', age: 30 }
];
persons.sort((a, b) => a.age - b.age);
console.log(persons);
// 输出:
// [
//   { name: 'Bob', age: 20 },
//   { name: 'Alice', age: 25 },
//   { name: 'Charlie', age: 30 }
// ]

In the above example, we first use the function to sort the sort()array of numbers , and since no comparison function is provided, it sorts according to the default sort order (using string comparison). numbersFor string arrays fruits, it is also sorted according to the default sort order. In the final sorting of the object array, we use the comparison function to sort the object array personsby attribute, from small to large.age

Note that sort()the function modifies the original array directly and returns the sorted array.

includes() and indexOf() functions

When we need to find out whether the specified element is contained in the array, we can use two commonly used functions provided by JavaScript: includes()and indexOf().

includes()The function is used to determine whether the specified element is contained in the array and returns a Boolean value. Returns if the specified element is contained in the array true; returns if the specified element is not contained in the array false.

indexOf()The function is used to find the index position of the specified element in the array and return the index value. If the array contains the specified element, returns the index of the first occurrence of the element; if the array does not contain the specified element, returns -1.

The following code uses the includes()and indexOf()function to find whether a specified element is contained in an array:

const fruits = ['apple', 'banana', 'orange', 'grape'];

// 使用includes()函数判断数组中是否包含指定元素
console.log(fruits.includes('apple')); // 输出: true
console.log(fruits.includes('mango')); // 输出: false

// 使用indexOf()函数查找指定元素在数组中的索引位置
console.log(fruits.indexOf('banana')); // 输出: 1
console.log(fruits.indexOf('watermelon')); // 输出: -1

In the above code, we use includes()the function to determine whether the array contains 'apple'and 'mango'two elements, and return trueand respectively false. Then use indexOf()the function to find 'banana'the 'watermelon'index position of the two elements in the array, and return the sum 1respectively -1.

It should be noted that includes()function and indexOf()function are case-sensitive, that is 'apple', and 'Apple'are different elements. If you need to search regardless of case, you can first convert the elements in the array to lowercase or uppercase, and then search.

slice() and splice() functions

slice()Both splice()can be used to truncate and delete elements of an array, but there are some important differences.

slice()The function is used to extract the specified range of elements from the array and return a new array, the original array will not be modified. slice()The function accepts two parameters, the index to start truncation and the index to end truncation (not included in the truncation range). If only one parameter is passed, it will be truncated from that index to the end of the array.

The following code uses slice()a function to truncate an array:

const fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi'];

const slicedFruits = fruits.slice(1, 4);
console.log(slicedFruits); // 输出: ['banana', 'orange', 'grape']

const slicedFruits2 = fruits.slice(2);
console.log(slicedFruits2); // 输出: ['orange', 'grape', 'kiwi']

splice()The function is used to delete elements in the array, and can insert new elements at the deleted positions. splice()The function takes three arguments, the index to start deleting, the number of elements to delete, and optionally the element to insert. If only two arguments are passed, only the specified number of elements will be removed.

The following code uses splice()a function to delete array elements:

const numbers = [1, 2, 3, 4, 5];

numbers.splice(2, 1);
console.log(numbers); // 输出: [1, 2, 4, 5]

numbers.splice(1, 2, 6, 7);
console.log(numbers); // 输出: [1, 6, 7, 5]

Note : splice()The function modifies the original array, and slice()the function does not modify the original array, but returns a new array.

slice()Functions are used to intercept elements of an array and return a new array, while splice()functions are used to delete elements of an array and can insert new elements.

concat() and join() functions

concat()And function in JavaScript can be used when we need to merge arrays or concatenate array elements into a string join().

concat()Function to merge two or more arrays and return a new merged array without modifying the original arrays. It accepts any number of arguments, each of which can be an array or a value.

The following code uses concat()a function to combine arrays:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let arr3 = [7, 8, 9];

let mergedArray = arr1.concat(arr2, arr3);
console.log(mergedArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

In the above code, we use concat()a function to combine the three arrays defined above into a new array mergedArray.

Note : concat()The function does not modify the original array, but returns a new merged array.

join()function to concatenate all elements of an array into a string. It accepts an optional argument separatorspecifying the delimiter to concatenate elements, which defaults to comma. join()The function returns a string.

The code below uses join()a function to concatenate array elements into a string:

let arr = ['Hello', 'World', '!'];

let joinedString = arr.join(' ');
console.log(joinedString); // 'Hello World !'

NOTE : join()The function does not modify the original array, but returns a new string.

Guess you like

Origin blog.csdn.net/w137160164/article/details/131674114