在 for 循环中断中的 JavaScript 切换;冲突

Javascript switch within for-loop break; conflicts

本文关键字:JavaScript 切换 冲突 for 循环 中断      更新时间:2023-09-26

我在JavaScript中嵌套了带有循环的开关,如下所示:

for (var i = 0; i < checkBoxIds.length; i++) {
        if ($('#' + checkBoxIds[i]).prop('checked')) {
            var id = checkBoxIds[i];
            var assetCat = id.substring(0, 4);
            switch (id.substring(id.length - 3)) {
                case "scr":
                    if (!sscripts)
                        if (confirm("Name of scripts sub-folder (in shared) is not provided for " + assetCat + ". Press OK to Continue for others?"))
                            continue; else break; //else return
                    //Appending chrs or sets or props to scripts
                    switchAssets(sscripts, IdEnum.SCRIPTS);
                    break;
                case "shd":
                    if (!sshaders)
                        if (confirm("Name of shaders sub-folder (in shared) is not provided for " + assetCat + ". Press OK to Continue for others?"))
                            continue; else break; //else return
                    //Appending chrs or sets or props to shaders
                    switchAssets(sshaders, IdEnum.SHADERS);
                    break;
                case "sim":
                    if (!ssourceimages)
                        if (confirm("Name of sourceimages sub-folder (in shared) is not provided for " + assetCat + ". Press OK to Continue for others?"))
                            continue; else break; //else return
                    //Appending chrs or sets or props to sourceimages
                    switchAssets(ssourceimages, IdEnum.SOURCEIMAGES);
                    break;
                default:
            }
        }
    }
    //...Still doing something (else return; will never kiss this :D )
}

如果 !sscripts 是假的,我要求用户是否要继续其他复选框,如果他取消,我想打破循环并执行函数中的剩余语句。好像休息了;在为开关执行的确认对话框中,如何使其运行for循环。

任何建议将不胜感激。

这正是标签的用途:

theloop:
  for (var i = 0; i < checkBoxIds.length; i++) {
    ...
    switch (id.substring(id.length - 3)) {
      ...
        break theloop;
        // continue theloop;

而不是这个

 continue; else break; //else return

试试这个

continue; else break iWantHere;//与标签中断

将此标签添加到您希望控件所在的位置iWantHere

Example
 for(...)
 {
    switch('a')
    {
       case 'a': break iWantHere; // This will exit out of loop
       default:
    }
 }  
 iWantHere :
  // Rest of your code