标题有点令人困惑,很抱歉,所以我有一个数组,其中一个数组包含的内容比第二个数组多
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, 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 = Math.min(i, y.length - 1)
console.log(y[idx])
}
关于javascript - 如何遍历包含小于迭代器值的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66639863/