You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

do while循环失效导致页面刷新无限循环 音乐随机播放模式不生效

问题根因分析

  • 死循环、随机播放不生效的核心错误出现在fas fa-random分支的do...while逻辑里:
    • 循环体内部生成的随机数没有赋值给randIndex,每次循环都不会更新随机值
    • while判断条件误用赋值运算符=而非相等判断运算符===,会直接把musicIndex强制赋值为randIndex,导致判断条件永远为真,直接进入死循环
  • 冗余代码问题:点击事件第一个case "fas fa-redo"分支下多写了一个多余的break,随机分支下的const test = ...赋值语句无实际作用
  • 单曲循环分支潜在问题:原代码loadMusic(indexNumb)里的indexNumb未定义,应该用当前播放的musicIndex

修复后代码

HTML

<audio id="main-audio" src=""></audio>

JavaScript

let musicIndex = 1;
repeatBtn.addEventListener('click', (e) => {
  const getClass = repeatBtn.className;
  switch(getClass){
    case "fas fa-redo":
      repeatBtn.className = "fas fa-random";
      repeatBtn.setAttribute("title", "Playlist Shuffle")
      break;
    case "fas fa-random":
      repeatBtn.className = "fas fa-stop-circle";
      repeatBtn.setAttribute("title", "Song Repeat")
      break;
    case "fas fa-stop-circle":
      repeatBtn.className = "fas fa-redo";
      repeatBtn.setAttribute("title", "Song Looped")
      break;
  }
})

musicAudio.addEventListener('ended', () => {
  const getClass = repeatBtn.className;
  switch(getClass){
    case "fas fa-random":
      let randIndex;
      // 生成和当前播放索引不重复的随机值
      do{
        randIndex = Math.floor(Math.random() * allMusic.length) + 1;
      }while(musicIndex === randIndex);
      musicIndex = randIndex;
      loadMusic(musicIndex);
      playMusic();
      break;
    case "fas fa-stop-circle":
      musicAudio.currentTime = 0;
      loadMusic(musicIndex)
      playMusic();
      break;
    case "fas fa-redo":
      nextMusic()
      break;
  }
})

内容的提问来源于stack exchange,提问作者user15415841

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 23:12:01