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

JavaScript如何实现数组遍历完成后自动从头循环?

问题根因

你的取模运算%位置错误,状态更新函数setCurrentTimeIndex、setcurrentEpisodeIndex本身没有返回值(返回undefined),你当前的写法相当于对undefined做取模运算,最终会得到NaN。当索引越界后convertedflat[NaN]返回undefined,传给播放器的seekTo方法就会触发「非有限值」的类型错误。

另外还有三个隐藏问题:

  • 第二个状态更新的回调参数命名错误,你误用了prevTimeIndex作为剧集索引的入参名
  • 剧集索引的取模应该用episList的长度,而不是convertedflat的长度,避免两个数组长度不一致时出现异常
  • 你的useEffect没有加依赖数组,每次组件渲染都会触发seekTo,可能会导致异常跳转

修正代码

1. 按钮点击事件修正

<button
  className={style.next}
  onClick={() => {
    setCurrentTimeIndex((prevTimeIndex) => (prevTimeIndex + 1) % convertedflat.length);
    setcurrentEpisodeIndex((prevEpisodeIndex) => (prevEpisodeIndex + 1) % episList.length);

    // 注意:这里打印的是更新前的状态,因为React状态更新是异步的
    console.log(currentTimeIndex);
    console.log(currentEpisodeIndex);
  }}
>
  下一个
</button>

2. useEffect优化(可选,推荐修改)

给useEffect添加依赖和边界判断,避免无效执行和异常调用:

useEffect(() => {
  // 仅当播放器实例初始化完成、时间戳为合法数字时才执行跳转
  if (playerRef.current && typeof convertedflat[currentTimeIndex] === 'number') {
    playerRef.current.seekTo(convertedflat[currentTimeIndex], 'seconds');
  }
}, [currentTimeIndex]); // 仅在时间索引变化时执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:45:04