介绍Array.prototype.map(),Array.prototype.filter(),Array.prototype.findIndex()

Array.prototype.map()The following is an introduction to Array.prototype.filter()these Array.prototype.findIndex()array methods:

  1. Array.prototype.map()

map()method creates a new array whose result is the result of calling a provided function on each element in the array.

For example:

let array = [1, 2, 3, 4, 5];
let squares = array.map(x => x * x);
console.log(squares);  // 输出:[1, 4, 9, 16, 25]

In this example, map()the method iterates over each element in the array, multiplies each element by itself, and returns a new array.

  1. Array.prototype.filter()

filter()method creates a new array whose elements are checked by checking all elements in the specified array that meet the criteria.

For example:

let array = [1, 2, 3, 4, 5];
let evens = array.filter(x => x % 2 === 0);
console.log(evens);  // 输出:[2, 4]

In this example, filter()the method iterates over each element in the array and returns a new array containing only even numbers.

  1. Array.prototype.findIndex()

findIndex()Method returns the index of the first element in the array that satisfies the provided test function. Otherwise -1 is returned.

For example:

let array = [1, 2, 3, 4, 5];
let index = array.findIndex(x => x > 3);
console.log(index);  // 输出:3

In this example, findIndex()the method iterates through each element in the array, returning the index of the first element greater than 3.

None of the above three methods will modify the original array, but return a new array or value. They all receive a callback function as a parameter, and this callback function will operate on each element of the array.

Guess you like

Origin blog.csdn.net/m0_57236802/article/details/131000815