js常用的数组遍历方式
时间: 2023-10-22 21:03:39 浏览: 33
1. for循环
```
let arr = [1, 2, 3, 4];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
```
2. forEach方法
```
let arr = [1, 2, 3, 4];
arr.forEach(function(item) {
console.log(item);
});
```
3. map方法
```
let arr = [1, 2, 3, 4];
let newArr = arr.map(function(item) {
return item * 2;
});
console.log(newArr);
```
4. filter方法
```
let arr = [1, 2, 3, 4];
let newArr = arr.filter(function(item) {
return item > 2;
});
console.log(newArr);
```
5. reduce方法
```
let arr = [1, 2, 3, 4];
let sum = arr.reduce(function(prev, current) {
return prev + current;
}, 0);
console.log(sum);
```
6. for...of循环
```
let arr = [1, 2, 3, 4];
for (let item of arr) {
console.log(item);
}
```
7. for...in循环
```
let arr = [1, 2, 3, 4];
for (let index in arr) {
console.log(arr[index]);
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)