javascripts中的数组是用于存储不同类型元素的单个变量;可以使用多种方法来迭代数组,一起来学习下4种方法:
方法1:使用for循环
<script> Array = [ 1, 2, 3, 4, 5, 6 ]; for (index = 0; index < array.length; index++) { console.log(array[index]); } </script>
<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>






网友评论文明上网理性发言 已有0人参与
发表评论: