在前后端开发中,我们常常会操作集合类型的数据,而JS遍历List无疑是其中最为常见的操作之一。本文将从多个方面对JS遍历List做详细的阐述。
一、基本遍历方式
const list = ['a', 'b', 'c'];
for (let i = 0; i<list.length; i++) {
console.log(list[i]);
}
上述代码中使用了for循环遍历List,中间通过i变量索引每一个元素进行操作。这种方式是JS最基本的遍历方式,能够满足简单List的遍历需求。
二、forEach遍历方式
const list = ['a', 'b', 'c'];
list.forEach(item => {
console.log(item);
});
forEach是一种遍历数组的方式,可以接收一个函数作为参数。该遍历方式具有以下特点:
- 无需使用循环变量,简化代码。
- forEach不能像普通的循环一样在中途返回。
- 无法在forEach内部使用break表达式,需要使用return。
- 不会改变原数组的值,仅用于遍历。
三、for…in 和 for…of 遍历方式
const list = ['a', 'b', 'c'];
for (const index in list) {
console.log(list[index]);
}
for (const item of list) {
console.log(item);
}
两种方式均可以遍历List,但有以下区别:
- for…in遍历出的是List的index,for…of遍历出的是List的value。
- for…in遍历对象属性时输出的顺序不会按照对象属性的顺序输出,而for…of遍历数组时输出的顺序会按照数组元素顺序输出。
- for…in可以遍历对象属性,而for…of不能。
四、map遍历方式
const list = ['a', 'b', 'c'];
const newList = list.map(item => {
return item.toUpperCase();
});
console.log(newList); // ['A', 'B', 'C']
map可以将原数组映射为一个新的数组,具有以下特点:
- 通过传入一个函数,并且该函数返回一个新的值,来重新生成一个新的数组。
- 可以使用filter过滤一些满足特定条件的元素。
五、reduce遍历方式
const list = [1, 2, 3, 4, 5];
const result = list.reduce((total, num) => {
return total + num;
}, 0);
console.log(result); // 15
reduce可以通过累加计算得到一个新值,具有以下特点:
- 可以通过传入一个函数来对数组元素依次累加,得到一个新的值。
- 可以通过第二个参数,指定初始值。
六、多维List遍历
const list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
for (let i = 0; i < list.length; i++) {
for (let j = 0; j < list[i].length; j++) {
console.log(list[i][j]);
}
}
多维List遍历可以通过嵌套循环来实现。需要注意的是,内部循环的索引需要使用不同的变量。
七、Iterator遍历方式
function makeIterator(list) {
let nextIndex = 0;
return {
next() {
if (nextIndex < list.length) {
return {value: list[nextIndex++], done: false};
} else {
return {done: true};
}
}
};
}
const list = ['a', 'b', 'c'];
const it = makeIterator(list);
let result = it.next();
while (!result.done) {
console.log(result.value);
result = it.next();
}
Iterator是ES6推出的一种遍历方式,具有以下特点:
- 可以自定义数据遍历。
- 可以定义内部状态,可以让遍历暂停和继续。
八、async/await实现遍历
async function asyncForEach(list, callback) {
for (let i = 0; i < list.length; i++) {
await callback(list[i], i, list);
}
}
asyncForEach([1, 2, 3], async(item, index, list) => {
await new Promise(resolve => {
setTimeout(() => {
console.log(item);
resolve();
}, 1000);
});
});
通过async/await实现遍历具有以下特点:
- 可以将异步回调同步执行。
- 可以自定义回调函数的同时将异步代码注入其中。
结束语
通过以上八种方式,我们可以对JS遍历List有一个更深入和全面的理解。在开发过程中,我们需要灵活根据实际情况选择最适合的遍历方式,提高开发效率。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/238042.html
微信扫一扫
支付宝扫一扫