不执行 switch 语句中的所有情况

not executing all the cases in switch statement

我有一个对象数组,我需要将 0 索引对象附加到 div 并将 1 索引对象附加到另一个 div。使用初始案例本身的 switch case returns 不执行第二个索引

let arr = [{id:1,name:'test'},{id:2,name:'sample'}]
arr.forEach((obj,index) => {
  switch(index){
   case 0:
      $(".first p").text(obj.name)
   case 1:
      $(".second p").text(obj.name)
  }
})

在执行完第一个 case 之后 returns 没有执行 case 1?

提前致谢

您需要在您的案例中添加一个 break 语句,否则执行将只是 "fall-through":

let arr = [{id:1, name:'test'}, {id:2, name:'sample'}];

arr.forEach((obj, index) => {
  switch(index) {
   case 0:
      $(".first p").text(obj.name);
      break;
   case 1:
      $(".second p").text(obj.name);
      break;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first">
  <p/>
</div>
<div class="second">
  <p/>
</div>