0
点赞
收藏
分享

微信扫一扫

js中filter,map,forEach,indexOf的用法和区别详解

彭维盛 04-08 20:30 阅读 0

在JavaScript中,filter(), map(), forEach(), 和 indexOf() 是数组对象常用的方法,它们各自具有特定的用途。以下是关于这些方法的详细解释和它们之间的区别:

1. filter()

filter() 方法创建一个新数组,其包含通过所提供函数实现的测试的所有元素。

用法

let newArray = arr.filter(function(currentValue, index, arr) {
  // 返回 true 或 false
});

或者,使用箭头函数:

let newArray = arr.filter(currentValue => {
  // 返回 true 或 false
});

示例

let numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // 输出: [2, 4, 6]

2. map()

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

用法

let newArray = arr.map(function(currentValue, index, arr) {
  // 返回一个新值
});

或者,使用箭头函数:

let newArray = arr.map(currentValue => {
  // 返回一个新值
});

示例

let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // 输出: [2, 4, 6]

3. forEach()

forEach() 方法对数组的每个元素执行一次提供的函数。

用法

arr.forEach(function(currentValue, index, arr) {
  // 执行某些操作
});

或者,使用箭头函数:

arr.forEach(currentValue => {
  // 执行某些操作
});

示例

let numbers = [1, 2, 3];
numbers.forEach(num => console.log(num)); // 输出: 1, 2, 3

4. indexOf()

indexOf() 方法返回在数组中可以找到给定元素的第一个索引,如果不存在,则返回-1。

用法

let index = arr.indexOf(searchElement[, fromIndex]);

示例

let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
let index = numbers.indexOf(4); // 输出: 3
let fromIndexIndex = numbers.indexOf(4, 4); // 输出: 5
let notFoundIndex = numbers.indexOf(6); // 输出: -1

区别

  • 返回值filter()map() 返回一个新数组;forEach() 没有返回值(它主要用于执行某些操作,而不是生成新数组);indexOf() 返回元素的索引或-1(如果元素不存在)。
  • 用途filter() 用于筛选数组中的元素;map() 用于转换数组中的每个元素;forEach() 用于遍历数组并执行操作;indexOf() 用于查找数组中元素的索引。
  • 链式调用:由于 filter(), map(), 和 forEach() 都返回数组,因此它们可以链式调用其他数组方法。而 indexOf() 返回一个数字,因此不能链式调用其他数组方法。

希望这些解释和示例能帮助您更好地理解JavaScript中这些方法的用法和区别!

举报

相关推荐

0 条评论