javascript中数组遍历的方法

一、for循环

for (let i = 0; i < 5; i++) {
	console.log(i)
}

二、for……of循环

for...of 语句执行一个循环,该循环处理来自可迭代对象的值序列。可迭代对象包括内置对象的实例,例如 Array、String、TypedArray、Map、Set、NodeList(以及其他 DOM 集合),还包括 arguments 对象、由生成器函数生成的生成器,以及用户定义的可迭代对象。

点击查看代码
// 迭代数组
const arr = ["a", "b", "c"];
for (const element of arr) {
  console.log(element);
}

// 迭代字符串
const str = "abc";
for (const value of str) {
  console.log(value);
}
// 'a'
// 'b'
// 'c'

三、for……in循环

点击查看代码
const arr = [1,2,3]
for (let i = 0; i < arr.length; i++) {
	console.log(i)
}
// 0
// 1
// 2

四、forEach方法

该方法接受一个函数,用于对数组中的每个元素进行处理,该方法不返回值

点击查看代码
const arr = ['a','b','c']

arr.forEach(function(item, index) {
	console.log(`${index} - ${item}`)
});

// 0 - a
// 1 - b
// 2 - c

五、map方法

作用同forEach方法,但该方法会返回处理后的新数组

点击查看代码
const array1 = [1, 4, 9, 16];

// Pass a function to map
const map1 = array1.map((x) => x * 2);

console.log(map1);
// Expected output: Array [2, 8, 18, 32]

六、filter方法

点击查看代码
const arr = [1,2,3,4]

const result = arr.filter(function(item, index) {
	return item > 2; // 示例:筛选大于2的元素
});

	console.log(result)
// [3,4]

七、some和every方法

some方法测试数组中是否至少有一个元素通过由提供的函数实现的测试。every方法测试是否所有元素都通过测试:方法测试数组中是否至少有一个元素通过由提供的函数实现的测试。every方法测试是否所有元素都通过测试:

点击查看代码
const arr = [10,20,30,40]

let hasLargeNumbers = arr.some(function(item, index) {
	return item > 10; // 示例:检查是否有大于10的元素
});

let allLargeNumbers = arr.every(function(item, index) {
	return item > 10; // 示例:检查所有元素是否都大于10
});

console.log(hasLargeNumbers)	//true
console.log(allLargeNumbers)	//false

八、find和findIndex方法

find 方法返回数组中满足提供的测试函数的第一个元素的值,否则返回undefined
findIndex 方法返回数组中满足提供的测试函数的第一个元素的索引,否则返回-1

点击查看代码
const arr = [10,20,30,40]

let foundItem = arr.find(function(item, index) {
	return item > 20; // 示例:找到第一个大于20的元素
});

let foundIndex = arr.findIndex(function(item, index) {
	return item > 20; // 示例:找到第一个大于20的元素的索引
});

console.log(foundItem) // 30
console.log(foundIndex) // 2

九、reduce方法

常用作求和,接受两个参数,第一个是callbackFn,第二个是初始值

点击查看代码
const array1 = [1, 2, 3, 4]

const initialValue = 10

const sumWithoutInitial = array1.reduce((accumulator,currentValue) => accumulator + currentValue)

const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue
)

console.log(sumWithoutInitial) //10
console.log(sumWithInitial)	// 20
posted @ 2026-03-23 21:12  Black_Kitty  阅读(4)  评论(0)    收藏  举报