SoFunction
Updated on 2025-04-14

Summary of front-end JavaScript array methods (very detailed!)

1. Main array methods:

  • join(): Use the specified separator to splice each item in the array into a string
  • push(): Add new elements to the end of the array
  • pop(): Delete the last item of the array
  • shift(): Delete the first item of the array
  • unshift(): Add new element to the first position of the array
  • slice(): Find some elements according to the conditions
  • splice(): Add, delete and modify the array
  • fill(): Methods can fill one or more elements in an array with specific values
  • filter():"Filter" function
  • concat(): Used to concatenate two or more arrays
  • indexOf(): Detect the index of the position where the current value first appears in the array
  • lastIndexOf(): Detect the index of the position where the current value last appears in the array
  • every(): Determine whether each item in the array meets the conditions
  • some(): Determine whether there are items in the array that meet the conditions
  • includes(): Determine whether an array contains a specified value
  • sort(): Sort the elements of the array
  • reverse(): Inverse order of the array
  • forEach(): ES5 and the following loop through each item in the array
  • map(): ES6 loop through each item in the array
  • copyWithin(): Used to copy elements from the specified position of the array into another specified position of the array
  • find():Returns the matching value
  • findIndex():Return the index of the matching position
  • toLocaleString()、toString(): Convert array to string
  • flat()、flatMap(): Flat array
  • entries() 、keys() 、values():Transfer through the array

2. Specific use of various methods

()

In JavaScript,join()is a method of array objects, and its function is to concatenate all elements in the array into a string. You can specify a separator that is inserted between the elements of the array. If the delimiter is not specified, the comma ‘,’ will be used by default.

grammar:

([separator])
  • arr: The array of elements that need to be connected.
  • separator(Optional): A string used to separate array elements. If this parameter is omitted, the array elements will be separated by commas.

Example:

//Example 1: Use the default separatorconst fruits = ['Apple', 'Banana', 'Cherry'];
const result = ();
(result);
//Apple,Banana,Cherry

//Example 2: Specify the delimiterconst numbers = [1, 2, 3, 4, 5];
const customResult = ('-');
(customResult);
//1-2-3-4-5

//Example 3: Use empty string as delimiterconst letters = ['H', 'e', 'l', 'l', 'o'];
const noSeparatorResult = ('');
(noSeparatorResult);
//Hello

()

In JavaScript,push()is a method of array objects. Its main function is to add one or more elements at the end of the array and return the length of the new array. This method will directly modify the original array.

grammar:

(element1[, ...[, elementN]])
  • arr: The array to operate.
  • element1, ..., elementN: One or more elements to be added to the end of the array.

Example:

// Example 1: Add a single elementconst animals = ['dog', 'cat'];
const newLength = ('rabbit');
('New array length:', newLength); 
('Updated array:', animals); 
//New array length: 3//Updated array: ['dog', 'cat', 'rabbit']
// Example 2: Add multiple elementsconst numbers = [1, 2, 3];
const updatedLength = (4, 5);
('New array length:', updatedLength); 
('Updated array:', numbers); 
//New array length: 5//Updated array: [1, 2, 3, 4, 5]

()

In JavaScript,pop()is a method of array objects. Its function is to remove the last element of the array and return the removed element. If the array is empty,pop()The method will not report an error, but will returnundefined, and this method will directly modify the original array.

grammar:

()
  • arr: The array to operate.

Example:

// Example 1: Use pop() method for non-empty arraysconst fruits = ['apple', 'banana', 'cherry'];
const removedFruit = ();
('Remove element:', removedFruit);
('Updated array:', fruits);
//Remove element: cherry//Updated array: ['apple', 'banana']
// Example 2: Use pop() method for empty arraysconst emptyArray = [];
const result = ();
('Return value:', result);
('Array Status:', emptyArray);
//Return value: undefined//Array status: []

()

In JavaScript,shift()is a method of array objects. Its main function is to remove the first element of the array and return the removed element. If the array is empty,shift()The method will returnundefined, and the method will directly modify the original array.

grammar:

()
  • arr: The array to operate.

Example:

// Example 1: Use shift() method for non-empty arraysconst colors = ['red', 'green', 'blue'];
const removedColor = ();
('Remove element:', removedColor);
('Updated array:', colors);
//Remove element: red//Updated array: ['green', 'blue']
// Example 2: Use shift() method for empty arraysconst emptyArr = [];
const result = ();
('Return value:', result);
('Array Status:', emptyArr);
//Return value: undefined//Array status: []

()

In JavaScript,unshift()is a method of array objects, which is used to add one or more elements at the beginning of the array and return the length of the new array. This method will directly modify the original array.

grammar:

(element1[, ...[, elementN]])
  • arr: The array to operate.
  • element1, ..., elementN: One or more elements to be added to the beginning of the array.

Example:

// Example 1: Add a single elementconst numbers = [2, 3, 4];
const newLength = (1);
('The length of the new array:', newLength);
('Updated array:', numbers);
//The length of the new array: 4//Updated array: [1, 2, 3, 4]
// Example 2: Add multiple elementsconst fruits = ['banana', 'cherry'];
const updatedLength = ('apple', 'grape');
('The length of the new array:', updatedLength);
('Updated array:', fruits);
//The length of the new array: 4//Updated array: ['apple', 'grape', 'banana', 'cherry']

()

In JavaScript,slice()is a method of array object, used to extract some elements from the original array and form a new array without modifying the original array.

grammar:

([begin[, end]])
  • arr: The array to operate.
  • begin(Optional): Extract the starting index position of the element. If this parameter is omitted, the default starts from index 0. If it is a negative number, it indicates the position of the reciprocating starting from the end of the array, for example-1Represents the last element.
  • end(Optional): Extract the end index position of the element (not including the corresponding element of the index). If this parameter is omitted, thebeginAll elements to the end of the array. If it is a negative number, it indicates the position of the reciprocating number starting from the end of the array.

Example:

// Example 1: Omit parametersconst fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
const newFruits = ();
('Original array:', fruits);
('New array:', newFruits);
//Original array: ['apple', 'banana', 'cherry', 'date', 'elderberry']//New array: ['apple', 'banana', 'cherry', 'date', 'elderberry']
// Example 2: Specify the begin parameterconst numbers = [1, 2, 3, 4, 5];
const newNumbers = (2);
('Original array:', numbers);
('New array:', newNumbers);
//Original array: [1, 2, 3, 4, 5]//New array: [3, 4, 5]
// Example 3: Specify the begin and end parametersconst animals = ['cat', 'dog', 'elephant', 'fox', 'giraffe'];
const newAnimals = (1, 3);
('Original array:', animals);
('New array:', newAnimals);
//Original array: ['cat', 'dog', 'elephant', 'fox', 'giraffe']//New array: ['dog', 'elephant']
// Example 4: Use negative indexingconst colors = ['red', 'green', 'blue', 'yellow', 'purple'];
const newColors = (-3, -1);
('Original array:', colors);
('New array:', newColors);
//Original array: ['red', 'green', 'blue', 'yellow', 'purple']//New array: ['blue', 'yellow']

()

In JavaScript,fill()is a method of array objects that can fill one or more elements in an array with a fixed value. This method will directly modify the original array and return the modified array.

grammar:

(value[, start[, end]])
  • arr: The array to operate.
  • value: Used to fill the value of the array element.
  • start(Optional): The index position at which to start filling is 0 by default. If it is a negative number, it indicates the position where the countdown starts from the end of the array.
  • end(Optional): The index position at which the end padding is filled (not including the corresponding element of the index), defaults to the length of the array. If it is a negative number, it indicates the position where the countdown starts from the end of the array.

Example:

// Example 1: Fill the entire array with one valueconst numbers = [1, 2, 3, 4, 5];
const filledNumbers = (0);
('Original array (modified):', numbers);
('The array returned after filling:', filledNumbers);
//The original array (has been modified): [0, 0, 0, 0, 0]//The returned array after filling: [0, 0, 0, 0, 0]
// Example 2: Specify the start and end positions for fillingconst letters = ['a', 'b', 'c', 'd', 'e'];
const filledLetters = ('x', 1, 3);
('Original array (modified):', letters);
('The array returned after filling:', filledLetters);
//The original array (modified): ['a', 'x', 'x', 'd', 'e']//The array returned after filling: ['a', 'x', 'x', 'd', 'e']
// Example 3: Use negative index for fillingconst colors = ['red', 'green', 'blue', 'yellow', 'purple'];
const filledColors = ('orange', -2);
('Original array (modified):', colors);
('The array returned after filling:', filledColors);
//The original array (modified): ['red', 'green', 'blue', 'orange', 'orange']//The returned array after filling: ['red', 'green', 'blue', 'orange', 'orange']

()

In JavaScript,filter()is a method of array objects. Its main function is to create a new array. The elements in the new array are all elements in the original array that meet the specified conditions.filter()The method does not change the original array, but returns a new array.

grammar:

(callback(element[, index[, array]])[, thisArg])
  • arr: The array to operate.
  • callback: The function used to test each element of the array, it receives three parameters:
    • element: The array element currently being processed.
    • index(Optional): The index of the current element.
    • array(Optional): Callfilter()Array of methods.
  • thisArg(Optional): ExecutecallbackUsed when using functionsthisValue

Example:

// Example 1: Filter out even numbers in the arrayconst numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = (function (number) {
    return number % 2 === 0;
});
('Original array:', numbers);
('Filtered even array:', evenNumbers);
//Original array: [1, 2, 3, 4, 5, 6]//Filtered even array: [2, 4, 6]

// Example 2: Filter elements using arrow functions and indexesconst words = ['apple', 'banana', 'cherry', 'date'];
const longWords = ((word, index) => {
    return  > 5 && index % 2 === 0;
});
('Original array:', words);
('Array of filtered long words with even index:', longWords);
//Original array: ['apple', 'banana', 'cherry', 'date']//Array with filtered long words and indexed as even numbers: ['cherry']

// Example 3: Filter out objects that meet the conditions in the object arrayconst users = [
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 30 },
    { name: 'Charlie', age: 22 }
];
const adults = (user =>  >= 25);
('Original array:', users);
('Filtered adult array:', adults);
//Original array: [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 22 } ]//Filtered adult array: [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 } ]

()

In JavaScript,concat()is a method of array objects, and its purpose is to connect two or more arrays to form a new array. This method does not change the original array, but returns a brand new array that contains the original array and all elements of the connected array.

grammar:

const newArray = (value1[, value2[, ...[, valueN]]])
  • oldArray: Callconcat()The original array of methods.
  • value1, value2, ..., valueN(Optional): To connect tooldArrayThe end array or value. If these parameters are arrays, their elements are added to the new array one by one; if they are other values, they are directly added to the end of the new array.

Example:

// Example 1: Concatenate two arraysconst array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const newArray = (array2);
('Original array 1:', array1);
('Original array 2:', array2);
('The new array after connection:', newArray);
//Original array 1: [1, 2, 3]//Original array 2: [4, 5, 6]//The new array after connection: [1, 2, 3, 4, 5, 6]
// Example 2: Connect multiple arraysconst firstArray = ['a', 'b'];
const secondArray = ['c', 'd'];
const thirdArray = ['e', 'f'];
const combinedArray = (secondArray, thirdArray);
('Original array 1:', firstArray);
('Original array 2:', secondArray);
('Original array 3:', thirdArray);
('The new array after connection:', combinedArray);
//Original array 1: ['a', 'b']//Original array 2: ['c', 'd']//Original array 3: ['e', 'f']//The new array after connection: ['a', 'b', 'c', 'd', 'e', ​​'f']
// Example 3: Concatenate arrays and valuesconst originalArray = [10, 20];
const newArrayWithValue = (30, [40, 50]);
('Original array:', originalArray);
('The new array after connection:', newArrayWithValue);
//Original array: [10, 20]//The new array after connection: [10, 20, 30, 40, 50]
    

()

In JavaScript,indexOf()is a method of an array object that is used to find the index position where a specified value first appears in the array. If the value exists in the array, it returns its index; if it does not exist, it returns-1. This method performs a strict equality comparison (i.e.===)。

grammar:

(searchElement[, fromIndex])
  • arr: The array to perform the search operation.
  • searchElement: Elements that need to be found in the array.
  • fromIndex(Optional): The index position to start searching, the default value is0. If the value is a negative number, the search starts from the corresponding position of the reciprocating end of the array, but the search order is still from front to back.

Example:

// Example 1: Basic Searchconst fruits = ['apple', 'banana', 'cherry', 'banana'];
const index = ('banana');
('Array:', fruits);
('"banana" index for the first time:', index);
//Array: ['apple', 'banana', 'cherry', 'banana']//"banana" first appearance index: 1
// Example 2: Specify the starting index searchconst numbers = [10, 20, 30, 20, 40];
const newIndex = (20, 2);
('Array:', numbers);
('From index 2, the first time it appears "20" index:', newIndex);
//Array: [10, 20, 30, 20, 40]//From index starting from index 2, the first index of "20" appears: 3
// Example 3: Finding non-existent elementsconst colors = ['red', 'green', 'blue'];
const nonExistentIndex = ('yellow');
('Array:', colors);
('"yellow" index for the first time:', nonExistentIndex);
//Array: ['red', 'green', 'blue']//"yellow" The first index appears: -1

()

In JavaScript,lastIndexOf()is a method of array objects, and its main function is to find the index position where the specified element last appears in the array. If this element exists in the array, it returns the index of its last occurrence; if it does not exist, it returns-1. This method performs a strict equality comparison (i.e.===)。

grammar:

(searchElement[, fromIndex])
  • arr: The array to perform the search operation.
  • searchElement: Elements that need to be found in the array.
  • fromIndex(Optional): Index position to start the reverse search. The default value is to minus the length of the array by 1, which means to search from the last element of the array. If this value is a negative number, the reverse search starts from the corresponding position of the reciprocating end of the array.

Example:

// Example 1: Basic Searchconst fruits = ['apple', 'banana', 'cherry', 'banana'];
const lastIndex = ('banana');
('Array:', fruits);
('"banana" last index:', lastIndex);
//Array: ['apple', 'banana', 'cherry', 'banana']//"banana" last appeared index: 3
// Example 2: Specify the starting index searchconst numbers = [10, 20, 30, 20, 40];
const newLastIndex = (20, 2);
('Array:', numbers);
('From the reverse search starting from index 2, "20" last index appears:', newLastIndex);
//Array: [10, 20, 30, 20, 40]//From the reverse search starting from index 2, "20" last appears index: 1
// Example 3: Finding non-existent elementsconst colors = ['red', 'green', 'blue'];
const nonExistentLastIndex = ('yellow');
('Array:', colors);
('"yellow" last index:', nonExistentLastIndex);
//Array: ['red', 'green', 'blue']//"yellow" The last index appears: -1

()

In JavaScript,every()is a method of array objects. It is used to detect whether all elements in the array meet the specified conditions. This method will execute the provided test function on each element in the array once, if all elements return the test function.true,butevery()Method returntrue;As long as there is an element, the test function returnsfalse, it will immediately stop traversing and returnfalse. This method does not change the original array.

grammar:

(callback(element[, index[, array]])[, thisArg])
  • arr: The array to be detected.
  • callback: The function used to test each element, it receives three parameters:
    • element: The array element currently being processed.
    • index(Optional): The index of the current element.
    • array(Optional): Callevery()Array of methods.
  • thisArg(Optional): ExecutecallbackUsed when using functionsthisValue.

Example:

// Example 1: Check whether all elements in the array are larger than 0const numbers = [1, 2, 3, 4, 5];
const allPositive = (function (number) {
    return number > 0;
});
('Array:', numbers);
('Are all elements in the array greater than 0:', allPositive);
//Array: [1, 2, 3, 4, 5]//Are all elements in the array greater than 0: true
// Example 2: Use the arrow function to check whether all elements in the array are longer than 3const words = ['apple', 'banana', 'cherry'];
const allLongWords = (word =>  > 3);
('Array:', words);
('Are all elements in the array longer than 3:', allLongWords);
//Array: ['apple', 'banana', 'cherry']//Are all elements in the array longer than 3: true
// Example 3: Check whether all elements in the array are even numbersconst mixedNumbers = [2, 4, 6, 7];
const allEven = (num => num % 2 === 0);
('Array:', mixedNumbers);
('Are all elements in the array even numbers:', allEven);
//Array: [2, 4, 6, 7]//Are all elements in the array even numbers: false    

()

In JavaScript,some()is a method of array objects that detects whether at least one element in the array meets the specified conditions. It will execute the test function you provide in turn on each element in the array, as long as there is an element that causes the test function to return.truesome()The method will return immediatelytrue;If all elements return the test functionfalse,butsome()Method returnfalse. This method does not change the original array.

grammar:

(callback(element[, index[, array]])[, thisArg])
  • arr: The array to be detected.
  • callback: The function used to test each element, which receives three parameters:
    • element: The array element currently being processed.
    • index(Optional): The index of the current element.
    • array(Optional): Callsome()Array of methods.
  • thisArg(Optional): ExecutecallbackUsed when using functionsthisValue.

Example:

// Example 1: Check if there are elements in the array greater than 5const numbers = [1, 3, 7, 4];
const hasGreaterThanFive = (function (number) {
    return number > 5;
});
('Array:', numbers);
('Is there any element in the array greater than 5:', hasGreaterThanFive);
//Array: [1, 3, 7, 4]//Is there any element in the array greater than 5: true
// Example 2: Use the arrow function to check whether there are elements in the array with a length of less than 3const words = ['apple', 'cat', 'banana'];
const hasShortWord = (word =>  < 3);
('Array:', words);
('Is there any element in the array that is less than 3:', hasShortWord);
//Array: ['apple', 'cat', 'banana']//Is there any element in the array that is less than 3: false
// Example 3: Check if there are even numbers in the arrayconst mixedNumbers = [1, 3, 5, 8];
const hasEvenNumber = (num => num % 2 === 0);
('Array:', mixedNumbers);
('Is there an even number in the array:', hasEvenNumber);
//Array: [1, 3, 5, 8]//Is there an even number in the array: true

()

In JavaScript,includes()is a method of array objects, which is used to determine whether an array contains a specified value. If included, returntrue, if not included, returnfalse. This method performs a strict equality comparison (i.e.===) and can specify which index position to start the search.

grammar:

(valueToFind[, fromIndex])
  • arr: The array to be checked.
  • valueToFind: The value that needs to be found in the array.
  • fromIndex(Optional): The index position to start searching, the default value is0. If the value is a negative number, the search starts from the corresponding position of the reciprocating end of the array, but the search order is still from front to back. likefromIndexThe absolute value of  is greater than the length of the array and will be directly indexed0Start searching.

Example:

// Example 1: Basic Searchconst fruits = ['apple', 'banana', 'cherry'];
const hasBanana = ('banana');
('Array:', fruits);
('Does "banana" be included in the array:', hasBanana);
//Array: ['apple', 'banana', 'cherry']//Is "banana" included in the array?
// Example 2: Specify the starting index searchconst numbers = [10, 20, 30, 20];
const hasTwentyFromIndexTwo = (20, 2);
('Array:', numbers);
('Start from index 2, whether the array contains "20":', hasTwentyFromIndexTwo);
//Array: [10, 20, 30, 20]//Start from index 2, whether the array contains "20": true
// Example 3: Finding non-existent elementsconst colors = ['red', 'green', 'blue'];
const hasYellow = ('yellow');
('Array:', colors);
('Does "yellow" be included in the array:', hasYellow);
//Array: ['red', 'green', 'blue']//Is the array containing "yellow": false
// Example 4: Find with negative indexconst letters = ['a', 'b', 'c', 'd'];
const hasBFromNegativeIndex = ('b', -3);
('Array:', letters);
('Start from the third last position, whether the array contains "b":', hasBFromNegativeIndex);
//Array: ['a', 'b', 'c', 'd']//From the last 3 Start searching for locations,Whether the array contains "b": true

()

In JavaScript,sort()is a method of array objects that sort elements of an array. By default,sort()The method converts array elements into strings and sorts them in Unicode encoding order. This means that if you use it directly on the array of numberssort()Method, the expected number size sorting result may not be obtained. However, you can define custom sorting rules by passing in a comparison function.sort()The method will directly modify the original array and return the sorted array.

grammar:

([compareFunction])
  • arr: The array to be sorted.
  • compareFunction(Optional): Comparison function to define collation. This function receives two parametersaandb, represents two elements in the array, and determines the order of the elements according to the positive and negative return value:
    • If the return value is less than 0,aWill be arranged tobBefore.
    • If the return value is equal to 0, thenaandbThe relative position remains unchanged.
    • If the return value is greater than 0,bWill be arranged toaBefore.

Example:

// Example 1: Default sort (in Unicode encoding order)const fruits = ['banana', 'apple', 'cherry'];
const sortedFruits = ();
('Original array (modified):', fruits);
('The array returned after sorting:', sortedFruits);
//The original array (modified): ['apple', 'banana', 'cherry']//The array returned after sorting: ['apple', 'banana', 'cherry']
// Example 2: Use default sorting for arrays of numbersconst numbers = [10, 5, 2, 20];
const defaultSortedNumbers = ();
('Original array (modified):', numbers);
('The array returned after default sorting:', defaultSortedNumbers);
//The original array (modified): [10, 2, 20, 5]//The array returned after default sorting: [10, 2, 20, 5]
// Example 3: Sort arrays of numbers using comparison functionsconst newNumbers = [10, 5, 2, 20];
const ascendingSortedNumbers = ((a, b) => a - b);
('Original array (modified):', newNumbers);
('Array returned after sorting ascending order:', ascendingSortedNumbers);
//The original array (modified): [2, 5, 10, 20]//The array returned after sorting ascending order: [2, 5, 10, 20]
// Example 4: Use the comparison function to sort the array of numbers in descending orderconst anotherNumbers = [10, 5, 2, 20];
const descendingSortedNumbers = ((a, b) => b - a);
('Original array (modified):', anotherNumbers);
('The array returned after descending order:', descendingSortedNumbers);
//The original array (modified): [20, 10, 5, 2]//The array returned after descending order: [20, 10, 5, 2]

()

In JavaScript,reverse()is a method of array objects, and its main function is to reverse the order of elements in an array. This method will directly modify the original array, reverse the arrangement order of the array elements, and finally return the modified original array

grammar:

()
  • arr: The array to perform the inverted element order.

Example:

// Example 1: Use reverse() method for normal arraysconst numbers = [1, 2, 3, 4, 5];
const reversedNumbers = ();
('Original array (modified):', numbers);
('The array returned after inversion:', reversedNumbers);
//The original array (modified): [5, 4, 3, 2, 1]//The array returned after inversion: [5, 4, 3, 2, 1]
// Example 2: Use reverse() method for string arraysconst fruits = ['apple', 'banana', 'cherry'];
const reversedFruits = ();
('Original array (modified):', fruits);
('The array returned after inversion:', reversedFruits);
//The original array (modified): ['cherry', 'banana', 'apple']//The returned array after inversion: ['cherry', 'banana', 'apple']

()

In JavaScript,forEach()is a method of array objects that are used to execute the provided function once on each element of an array.forEach()The method has no return value, and its main purpose is to iterate over the array elements and perform specific operations on each element. This method calls the callback function you provide once for each element in the array, and does not change the original array.

grammar:

(callback(currentValue[, index[, array]])[, thisArg])
  • arr: The array to be traversed.
  • callback: A function executed for each element in the array, which receives three parameters:
    • currentValue: The array element currently being processed.
    • index(Optional): The index of the current element.
    • array(Optional): CallforEach()Array of methods.
  • thisArg(Optional): ExecutecallbackUsed when using functionsthisValue.

Example:

// Example 1: Simple traversal of the array and print elementsconst numbers = [1, 2, 3, 4, 5];
(function (number) {
    (number);
});
//1
//2
//3
//4
//5

// Example 2: Use index and array parametersconst fruits = ['apple', 'banana', 'cherry'];
(function (fruit, index, array) {
    (`index ${index} The element at ${fruit},The array is ${array}`);
});
//The element at index 0 is apple, and the array is apple,banana,cherry//The element at index 1 is banana, and the array is apple,banana,cherry//The element at index 2 is cherry, and the array is apple,banana,cherry
// Example 3: Use arrow functions and accumulation operationslet sum = 0;
const newNumbers = [10, 20, 30];
((number) => {
    sum += number;
});
('The sum of array elements is:', sum);
//The sum of array elements is: 60

()

In JavaScript,map()is a method of array objects. It is used to create a new array. The elements in the new array are the result of each element in the original array being processed by a specified function. That is to say,map()The method will call the callback function you provide in turn for each element of the original array, and use the return value of the callback function as the element at the corresponding position of the new array. This method does not change the original array.

grammar:

(callback(currentValue[, index[, array]])[, thisArg])
  • arr: The original array to be operated on.
  • callback: A function executed for each element in the array, which receives three parameters:
    • currentValue: The array element currently being processed.
    • index(Optional): The index of the current element.
    • array(Optional): Callmap()Array of methods.
  • thisArg(Optional): ExecutecallbackUsed when using functionsthisValue.

Example:

// Example 1: Multiply each element in the array by 2const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = (function (number) {
    return number * 2;
});
('Original array:', numbers);
('New array (multiple each element by 2):', doubledNumbers);
//Original array: [1, 2, 3, 4, 5]//New array (each element is multiplied by 2): [2, 4, 6, 8, 10]
// Example 2: Use arrow functions and index parametersconst names = ['Alice', 'Bob', 'Charlie'];
const nameWithIndex = ((name, index) => `${index + 1}. ${name}`);
('Original array:', names);
('New array (add index):', nameWithIndex);
//Original array: ['Alice', 'Bob', 'Charlie']//New array (add index): ['1. Alice', '2. Bob', '3. Charlie']
// Example 3: Processing object arrayconst users = [
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 30 },
    { name: 'Charlie', age: 22 }
];
const userAges = (user => );
('Original array:', users);
('New array (including age only):', userAges);
//Original array: [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 22 } ]//New array(Includes only age): [25, 30, 22]

()

In JavaScript,copyWithin()is a method of an array object. It is used to copy elements at the specified position to another location inside the array (overwrite the original element) and return the modified original array. This method will directly modify the original array and will not change the length of the array.

grammar:

(target[, start[, end]])
  • arr: The array to be operated on.
  • target: Copy the sequence to this location. If it is a negative number,targetThe calculation will start from the end of the array.
  • start(Optional): Starting the start position of the element. The default value is 0. If it is a negative number,startThe calculation will start from the end of the array.
  • end(Optional): Stop copying the end position of the element (excluding the element at that position). The default value is the length of the array. If it is a negative number,endThe calculation will start from the end of the array.

Example:

// Example 1: Simple copyconst numbers = [1, 2, 3, 4, 5];
// Start copying the element from index 0 and copying to the location of index 3const result = (3);
('Modified array:', result);
//Modified array: [1, 2, 3, 1, 2]
// Example 2: Specify the start and end positions to copyconst letters = ['a', 'b', 'c', 'd', 'e'];
// Start copying from index 1, and stop copying to index 3, and copying to the location of index 0const newResult = (0, 1, 3);
('Modified array:', newResult);
//Modified array: ['b', 'c', 'c', 'd', 'e']
// Example 3: Copy with negative indexconst colors = ['red', 'green', 'blue', 'yellow', 'purple'];
// Copy from the second end element to the fourth end elementconst finalResult = (-4, -2);
('Modified array:', finalResult);
//Modified array: ['red', 'yellow', 'purple', 'yellow', 'purple']    

()

In JavaScript,find()is a method of an array object, which is used to find the first element in an array that meets the specified conditions. This method will execute the test function you provide in turn on each element in the array, and once a certain element causes the test function to returntruefind()The method will return the element immediately; if there is no element in the array, the test function can returntrue, then returnundefinedfind()The method will not change the original array.

grammar:

(callback(element[, index[, array]])[, thisArg])
  • arr: The array to perform the search operation.
  • callback: The function used to test each element, which receives three parameters:
    • element: The array element currently being processed.
    • index(Optional): The index of the current element.
    • array(Optional): Callfind()Array of methods.
  • thisArg(Optional): ExecutecallbackUsed when using functionsthisValue.

Example:

// Example 1: Find the first element in the array that is greater than 5const numbers = [1, 3, 7, 4, 9];
const firstGreaterThanFive = (function (number) {
    return number > 5;
});
('Array:', numbers);
('The first element in the array that is greater than 5:', firstGreaterThanFive);
//Array: [1, 3, 7, 4, 9]//The first element in the array with a larger than 5: 7
// Example 2: Use arrow function to find the first user older than 25 in the object arrayconst users = [
    { name: 'Alice', age: 22 },
    { name: 'Bob', age: 28 },
    { name: 'Charlie', age: 20 }
];
const firstUserOver25 = (user =>  > 25);
('Array:', users);
('The first user in the array with age greater than 25:', firstUserOver25);
//Array: [ { name: 'Alice', age: 22 }, { name: 'Bob', age: 28 }, { name: 'Charlie', age: 20 } ]//The first user in the array with age greater than 25: { name: 'Bob', age: 28 }
// Example 3: Finding non-existent elementsconst letters = ['a', 'b', 'c'];
const nonExistentElement = (letter => letter === 'd');
('Array:', letters);
('Find the result:', nonExistentElement);
//Array: ['a', 'b', 'c']//Find results: undefined

()

In JavaScript,findIndex()is a method of array objects, and its function is to find the index of the first element in the array that meets the specified conditions. It will execute the test function you provide in turn on each element in the array, and once a certain element causes the test function to returntruefindIndex()The method will immediately return the index of the element; if there is no element in the array, the test function can returntrue, then return-1. This method does not change the original array.

grammar:

  • arr: The array to perform the search operation.
  • callback: The function used to test each element, which receives three parameters:
    • element: The array element currently being processed.
    • index(Optional): The index of the current element.
    • array(Optional): CallfindIndex()Array of methods.
  • thisArg(Optional): ExecutecallbackUsed when using functionsthisValue.

Example:

// Example 1: Find the index of the first element in the array that is greater than 10const numbers = [5, 8, 12, 3, 15];
const index = (function (number) {
    return number > 10;
});
('Array:', numbers);
('Index of the first element in the array greater than 10:', index);
//Array: [5, 8, 12, 3, 15]//The index of the first element greater than 10 in the array: 2
// Example 2: Use arrow functions to find the index of the first user older than 25 in the object arrayconst users = [
    { name: 'Alice', age: 22 },
    { name: 'Bob', age: 28 },
    { name: 'Charlie', age: 20 }
];
const userIndex = (user =>  > 25);
('Array:', users);
('Index for the first user older than 25 in the array:', userIndex);
//Array: [ { name: 'Alice', age: 22 }, { name: 'Bob', age: 28 }, { name: 'Charlie', age: 20 } ]//The index of the first user older than 25 in the array: 1
// Example 3: Find the index of non-existent elementsconst letters = ['a', 'b', 'c'];
const nonExistentIndex = (letter => letter === 'd');
('Array:', letters);
('Find the result:', nonExistentIndex);
//Array: ['a', 'b', 'c']//Find results: -1

Summarize

This is the end of this article about front-end JavaScript array method. For more related front-end js array method content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!