JavaScript 数组系列讲解 V - 数组循环与迭代(第二部分)
在上一篇文章中,我讨论了如何使用逗号和For ...循环遍历数组。您可以在下面查看:For ... ofFor ... in
本文将介绍遍历数组的另外两种方法。
1. While 循环
while 循环会创建一个迭代过程,只要指定的条件为真,就会执行指定的语句。在执行语句之前,总是会检查指定的条件。
// syntax
while ( conditon ) {
[statement]
}
[条件]:这是一个表达式,在每次循环执行语句之前都会执行。只要条件为真,循环就会继续;当条件为假时,循环就会终止,程序会继续执行 while 循环之后的语句。
[语句]:只要条件为真,就会执行此语句。
要使用循环遍历数组while,条件将是数组长度的递减表达式(例如arrayLength--)。下面是一些示例。
const players = ["messi", "ronaldo", "nedy", "kante"];
let index = players.length;
while (index--) {
console.log(players[index]) // "kante", "nedy", "ronaldo", "messi"
}
这样做会从数组的最后一个元素开始访问。要达到预期效果,需要:
Array.prototype.reverse()使用如下所示的方法,在 while 循环之前反转数组。
const players = ["messi", "ronaldo", "nedy", "kante"];
// reverse the array
players.reverse();
let index = players.length;
while (index--) {
console.log(players[index]) // "messi", "ronaldo", "nedy", "kante"
}
- 将计数器初始化为 -1,以便在第一次运行时计数器递增至 0,请参见下方示例。
const players = ["messi", "ronaldo", "nedy", "kante"];
let index = -1;
while (index++ < players.length-1) {
console.log(players[index]) // "messi", "ronaldo", "nedy", "kante"
}
(感谢 @dovca 提出这个方法)。
1. 执行...while循环
该方法会先执行语句,然后再检查条件是否为真,直到指定的条件评估结果为假为止。
// syntax
do {
[statement]
}
while ( conditon )
使用do ... while循环遍历数组可能会比较棘手,因为指定的语句至少会在条件执行之前运行一次。请看下面的示例。
const players = ["messi", "ronaldo", "nedy", "kante"];
// reverse the array 0 1 2 3
players.reverse() // "kante", "nedy", "ronaldo", "messi"
let index = players.length;
// itereation
do {
console.log(players[index]) // undefined, "messi", "ronaldo", "nedy", "kante"
}
while (index--)
在这种情况下,由于语句在条件执行之前执行,导致 `size` 的值为 `undefined`,而4数组索引到 3 就结束了players[3] = "messi"。`continue` 函数用于跳过初始语句的执行,这样当它再次执行时,`size` 的值为 3,并且我们已经将结果messi输出到控制台。请看下面的示例。
const players = ["messi", "ronaldo", "nedy", "kante"];
// reverse the array 0 1 2 3
players.reverse() // "kante", "nedy", "ronaldo", "messi"
let index = players.length;
// itereation
do {
// skip the initial statement
if(index === players.length) {continue}
console.log(players[index]) // "messi", "ronaldo", "nedy", "kante"
}
while (index--)
[break] break 语句用于在条件判断为真之前终止循环。顾名思义,它会跳出循环。
[Continue]: continue 语句用于跳过循环中的一次迭代。
结论
while使用&do ... while循环遍历数组时需要考虑很多因素,我建议在必要之前最好使用其他迭代方法。
今天就到这里,明天我们将讨论数组迭代中使用的另一组函数。
以下是我撰写的关于数组系列的其他文章的链接:
有任何疑问、补充或更正吗?请留言。
感谢阅读。👍
文章来源:https://dev.to/nedyudombat/understanding-javascript-array-series-iv-array-loops-iteration-part-ii-115o