【问题标题】:TypeError: array[i] is not iterable类型错误:数组 [i] 不可迭代
【发布时间】:2025-12-13 15:20:06
【问题描述】:

使用Javascript,我正在制作一个可以操作数组的函数......在函数中你可以输入(你想要操作的数组,运算符,你将操作的大小,数组的元素)...我正在测试增量运算符。这是代码

function manipulateArray(array=[],operator=null,magnitude=null,element=null)
{
    var newArray=[];
    if (operator=="increment")
    {
        for (var i=0;i<(array.length)-1;i++)
        {
            if (element-1==i)
            {
                newArray.pop();
                newArray=newArray.push(array[element-1]+magnitude);
                newArray.push(array[i+1]);
            }
            else {
                if(element==i)
                {
                newArray.pop();
                }
                newArray=[...array[i]].push(array[i+1]);
            }
        }
    }
    else 
    {
        newArray="INVALID INPUT!";
    }
    return newArray;

}
var t=[7,3,6,9];
console.log(manipulateArray(t,"increment",1,2));//expected output is [7,4,6,9];

预期的输出是 [7,4,6​​,9](作为将 1 增加到数组 t 的第二个元素的结果) 但是输出结果是

TypeError: array[i] is not iterable

请对代码进行必要的更改,以便它可以返回预期的输出并通常适用于任何非嵌套数组。

【问题讨论】:

  • array[i] 是一个数字。你为什么要尝试从数字中“提取”(...)一些东西?
  • “请对代码进行必要的更改...” - 阅读扩展运算符 (...) 所做的事情,您应该自己找出问题所在。
  • newArray=[...array[i]].push(array[i+1]); 首先应该做什么? [...array[i]] 将,如果 array[i] 是可迭代的,则将 array[i] 中的元素克隆到一个新数组中,将 array[i + 1] 推入该新数组中,并存储 .push() 的返回值(修改后的新长度)数组)在newArray - oO
  • 另外,push 在推入后返回数组的新长度,不是数组本身,因此newArray=newArray.push(array[element-1]+magnitude); 将整数分配给newArray,表示任何进一步的尝试将newArray 作为数组操作会失败。

标签: javascript arrays function manipulate


【解决方案1】:

这里我将magnitude添加到数组的第二个元素并返回数组。

顺便说一句:为了尽量减少混淆,我认为您应该让 element 跟随数组的索引 - 所以,第一个元素是索引 0。

function manipulateArray(array = [], operator = null, magnitude = null, element = null) {
  let newArray = [...array];
  if (operator == "increment") {
    newArray[element - 1] += magnitude;
  } else {
    newArray = "INVALID INPUT!";
  }
  return newArray;
}

var t = [7, 3, 6, 9];
console.log(manipulateArray(t, "increment", 1, 2)); //expected output is [7,4,6,9];

另一种方法是在数组中使用map()

function manipulateArray(array = [], operator = null, magnitude = null, element = null) {
  let newArray;
  if (operator == "increment") {
    newArray = array.map((s, i) => {
      return (i == element-1) ? s + magnitude : s;
    });
  } else {
    newArray = "INVALID INPUT!";
  }
  return newArray;
}

var t = [7, 3, 6, 9];
console.log(manipulateArray(t, "increment", 1, 2)); //expected output is [7,4,6,9];

【讨论】: