关于嵌套循环中的循环顺序


let myPlaces = ['Place1', 'Place2', 'Place3'];
let friendPlaces = ['Place4', 'Place5', 'Place6'];
for (let myPlacesIndex = 0; myPlacesIndex < myPlaces.length; myPlacesIndex++) {
console.log(myPlaces[myPlacesIndex]);
for (let friendPlacesIndex = 0; friendPlacesIndex < friendPlaces.length; friendPlacesIndex++) {
console.log(friendPlaces[friendPlacesIndex]);
}
}

我不明白内部"for 循环"一次完全循环背后的逻辑。我预计应该打印到控制台的顺序是:Place1,Place4,Place2,Place5,Place3,Place6。

有人可以向我解释为什么会这样吗?

因为for是一个同步循环。因此,当该指令出现时,它将在转到下一条指令之前执行所有循环。这意味着您的输出将是这样的:

//Place-1 -> out for loop 1
//Place-4
//Place-5
//Place-6
//Place-2 -> out for loop 2
//Place-4
//Place-5
//Place-6
//Place-3 -> out for loop 3
//Place-4
//Place-5
//Place-6

最新更新