如何遍历包含小于迭代器值的数组

问题描述

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

   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 长度一样多的内容

解决方法

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

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])
}

或者您可以使用 y 数组的最后一个索引,如果当前 i 值超过 y 数组中最后一个项目索引的长度:

const x = [1,"w":"test24"}]

for (let i = 0; i < x.length; i++) {
  const idx = Math.min(i,y.length - 1)
  console.log(y[idx])
}