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

时间:2018-08-09 19:00:04

标签: javascript for-loop

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。

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

1 个答案:

答案 0 :(得分:0)

因为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