提问者:小点点

如何在包含少于迭代器值的数组中进行迭代


标题有点混乱,很抱歉,所以我有一个太多的数组,其中一个数组比第二个数组包含更多

   x = [1,2,3,4,5];
    y =  [{
          x: "test1",
          y: "test2",
          z: "test3",
          w: `test4`
        }] 

所以我想做的是例如

 for (let i = 0; i < x.length; i++) {
     console.log(y[i])
}

这只会注销第一个一次,但我想要的是日志y和x长度一样多,希望这是足够清楚的


共1个答案

匿名用户

您可以使用剩余运算符从较短的数组中获取相应的项:

null

const x = [1, 2, 3, 4, 5];
const y = [{"x":"test1","y":"test2","z":"test3","w":"test4"},{"x":"test21","y":"test22","z":"test23","w":"test24"}]

for (let i = 0; i < x.length; i++) {
  const idx = i % y.length;
  console.log(y[idx])
}