跳到主要内容

数组遍历

3 分钟阅读

forEach

forEach()方法用于遍历数组中的每个元素,对每个元素执行指定的操作。与 map() 不同的是,forEach()不会返回一个新的数组,而是直接对原始数组进行操作。

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

numbers.forEach(function(num) {
console.log(num);
});

// Output:
// 1
// 2
// 3
// 4
// 5

map

map()方法是用于对数组中的每个元素进行转换,返回一个新的数组,该数组包含了每个元素被转换后的结果。具体来说,map()方法会遍历原始数组中的每个元素,将每个元素传递给回调函数进行处理,并将处理后的结果添加到新的数组中。原始数组不会被改变。

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function (num) {
return num * 2;
});
console.log(doubledNumbers); // [2, 4, 6, 8, 10]

filter

filter()方法是用于从数组中筛选出满足特定条件的元素,返回一个新的数组,该数组包含了符合条件的元素。具体来说,filter()方法会遍历原始数组中的每个元素,将每个元素传递给回调函数进行处理,如果回调函数返回 true,则该元素会被添加到新的数组中。原始数组不会被改变。

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(function (num) {
return num % 2 === 0;
});
console.log(evenNumbers); // [2, 4]

find

find()方法会返回数组中第一个满足给定测试函数的元素的值,否则返回 undefined

find()方法接受一个回调函数作为参数,该回调函数接受三个参数:

  1. element:当前遍历到的数组元素。
  2. index(可选):当前元素的索引。
  3. array(可选):正在操作的数组。

回调函数应该返回一个布尔值。如果返回 true,则 Array.prototype.find() 方法会返回当前遍历到的元素,如果没有找到满足条件的元素,则返回 undefined

const array = [1, 2, 3, 4, 5];
const found = array.find(element => element === 3);
console.log(found); // 3

for...of

for...of 是 JavaScript 中一种用于遍历可迭代对象的语法结构。它提供了一种更简洁、直观的方式来遍历数组、字符串、集合等可迭代对象的元素。

// 遍历数组
const myArray = [1, 2, 3];
for (const element of myArray) {
console.log(element);
}

// 遍历字符串
const myString = 'Hello';
for (const char of myString) {
console.log(char);
}

for...of 循环本身不提供直接的索引(index)访问。但可以通过结合使用数组的 entries 方法和解构赋值来获取索引和元素。

const myArray = ['a', 'b', 'c'];

for (const [index, element] of myArray.entries()) {
console.log(`Index: ${index}, Element: ${element}`);
}
评论
0条评论

添加新评论

昵称
邮箱
网址