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

以下是 Array.prototype.map(), Array.prototype.filter(), Array.prototype.findIndex() 这几个数组方法的介绍:

  1. Array.prototype.map()

map() 方法会创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。

例如:

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

在这个例子中,map() 方法遍历数组中的每个元素,并将每个元素乘以自身,然后返回一个新的数组。

  1. Array.prototype.filter()

filter() 方法创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

例如:

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

在这个例子中,filter() 方法遍历数组中的每个元素,并返回一个只包含偶数的新数组。

  1. Array.prototype.findIndex()

findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。否则返回-1。

例如:

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

在这个例子中,findIndex() 方法遍历数组中的每个元素,返回第一个大于 3 的元素的索引。

以上这三个方法都不会修改原数组,而是返回一个新的数组或值。它们都接收一个回调函数作为参数,这个回调函数会对数组的每个元素进行操作。

猜你喜欢

转载自blog.csdn.net/m0_57236802/article/details/131000815