JavaScript遍历数组的5种方式详细指南

2021年4月4日18:35:49 发表评论 604 次浏览

Javascript中的数组是用于存储不同类型元素的单个变量。

例如, 简单的数组访问可能如下所示:

<script>
array = [ 'geeks' , '4' , 'geeks' ];
  
// Accessing array elements one by one
console.log(array[0]);
console.log(array[1]);
console.log(array[2]);
</script>

输出如下:

geeks
4
geeks

有多种方法可以遍历Javascript中的数组,最有用的在下面提到,这里我们主要介绍JavaScript遍历数组的5种方式。

1. 使用for循环遍历数组

这类似于其他语言(例如C / C ++, Java等)中的for循环

<script>
array = [ 1, 2, 3, 4, 5, 6 ];
for (index = 0; index < array.length; index++) {
     console.log(array[index]);
}
</script>

输出如下:

1
2
3
4
5
6

2. JavaScript使用while循环遍历数组

这再次类似于其他语言。

<script>
index = 0;
array = [ 1, 2, 3, 4, 5, 6 ];
  
while (index < array.length) {
     console.log(array[index]);
     index++;
}</script>

输出如下:

1
2
3
4
5
6

3. JavaScript使用forEach方法遍历数组

forEach方法针对顺序中的每个数组元素调用一次提供的函数。

<script>
index = 0;
array = [ 1, 2, 3, 4, 5, 6 ];
  
array.forEach(myFunction);
function myFunction(item, index)
{
     console.log(item);
}</script>

输出如下:

1
2
3
4
5
6

4. JavaScript使用every()方法遍历数组

every()方法检查数组中的所有元素是否都通过测试(作为函数提供)。

<script>
index = 0;
array = [ 1, 2, 3, 4, 5, 6 ];
  
const under_five = x => x < 5;
  
if (array.every(under_five)) {
     console.log( 'All are less than 5' );
}
else {
     console.log( 'At least one element is not less than 5' );
}
</script>

输出如下:

At least one element is not less than 5.

5. JavaScript使用map方法遍历数组

map将函数应用于每个元素, 然后返回新数组。

<script>
index = 0;
array = [ 1, 2, 3, 4, 5, 6 ];
  
square = x => Math.pow(x, 2);
squares = array.map(square);
console.log(array);
console.log(squares);</script>

输出如下:

1 2 3 4 5 6 
1 4 9 16 25 36

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: