JS 数组遍历方法大全:for循环、forEach、map、for...in、for...of
JS 数组遍历方法大全:for循环、forEach、map、for...in、for...of
JavaScript 中有多种方法可以遍历数组,每种方法都有其优缺点,选择最适合你的方法取决于你的需求和习惯。本文将介绍常见的几种遍历方法,并提供代码示例。
1. for循环
使用 for循环 是最基础的遍历方法,代码如下:
let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
2. forEach方法
forEach() 方法是 ES5 新增的数组遍历方法,可以用来遍历数组中的每个元素。
let arr = [1, 2, 3, 4, 5];
arr.forEach(function (item, index, array) {
console.log(item, index);
});
3. map方法
map() 方法也是 ES5 新增的数组方法,它可以遍历数组中的每个元素,并返回一个新的数组。
let arr = [1, 2, 3, 4, 5];
let newArr = arr.map(function (item) {
return item * 2;
});
console.log(newArr); // [2, 4, 6, 8, 10]
4. for...in循环
for...in 循环可以用来遍历对象中的属性,也可以遍历数组中的索引。
let arr = [1, 2, 3, 4, 5];
for (let index in arr) {
console.log(arr[index]);
}
5. for...of循环
for...of 循环是 ES6 新增的遍历数组的方法,它可以用来遍历数组中的每个元素。
let arr = [1, 2, 3, 4, 5];
for (let item of arr) {
console.log(item);
}
总结
以上是常用的 JS 遍历数组的方式,具体使用哪种方式取决于你的需求和习惯。
原文地址: https://www.cveoy.top/t/topic/nvl7 著作权归作者所有。请勿转载和采集!