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

JavaScript数组循环:从指定索引生成环形新数组问题

问题解决:从指定元素开始循环生成新数组

你的现有代码仅遍历了目标索引到原数组末尾的元素,遗漏了数组开头到目标索引前的部分,因此只输出了后半段结果。以下是完善后的实现方案:

基础修正版本

function find_all_color() {
  var input = prompt("Enter any color");
  var colorArr = ['yellow', 'red','green', 'blue','white','orange', 'black'];
  var arrIndex = colorArr.indexOf(input);
  var newArr = [];

  // 处理输入颜色不在列表中的情况
  if (arrIndex === -1) {
    alert("输入的颜色不存在于列表中");
    return;
  }

  // 先添加目标索引到数组末尾的元素
  for (let i = arrIndex; i < colorArr.length; i++) {
    newArr.push(colorArr[i]);
  }
  // 再添加数组开头到目标索引前的元素
  for (let i = 0; i < arrIndex; i++) {
    newArr.push(colorArr[i]);
  }

  console.log(newArr);
}

find_all_color(); // 输入'white'时输出:['white', 'orange', 'black', 'yellow', 'red', 'green', 'blue']

更简洁的数组方法版本

利用数组原生的slice和concat方法,可以省去手动循环的步骤,代码更简洁高效:

function find_all_color() {
  var input = prompt("Enter any color");
  var colorArr = ['yellow', 'red','green', 'blue','white','orange', 'black'];
  var arrIndex = colorArr.indexOf(input);

  if (arrIndex === -1) {
    alert("输入的颜色不存在于列表中");
    return;
  }

  // 拼接目标索引到末尾的子数组、开头到目标索引前的子数组
  var newArr = colorArr.slice(arrIndex).concat(colorArr.slice(0, arrIndex));
  console.log(newArr);
}

find_all_color();

关键说明

  • 原代码缺陷:仅遍历了arrIndex到数组末尾的元素,未处理数组开头到arrIndex-1的部分。
  • 边界处理:增加了输入元素不存在时的判断,避免因arrIndex=-1引发的错误逻辑。
  • 简洁版原理:slice(arrIndex)提取目标索引到末尾的子数组,slice(0, arrIndex)提取开头到目标索引前的子数组,通过concat拼接两个子数组即可得到循环后的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:01:20