方法1:使用for循环
<script> array = [ 1, 2, 3, 4, 5, 6 ]; for (index = 0; index < array.length; index++) { console.log(array[index]); } </script>
输出:
方法2:使用while循环
<script> index = 0; array = [ 1, 2, 3, 4, 5, 6 ]; while (index < array.length) { console.log(array[index]); index++; } </script>
输出:
方法3:使用forEach方法
forEach方法可按顺序为每个数组元素调用一次所提供的函数。
<script> index = 0; array = [ 1, 2, 3, 4, 5, 6 ]; array.forEach(myFunction); function myFunction(item, index) { console.log(item); } </script>
输出:
方法4:使用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>
输出:
以上就是如何使用JavaScript迭代数组?的详细内容,更多请关注0133技术站其它相关文章!