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

标签 javascript node.js arrays for-loop iteration

标题有点令人困惑,很抱歉,所以我有一个数组,其中一个数组包含的内容比第二个数组多

   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/

相关文章:

python - Numpy中的均方误差?

JavaScript问题: functionName.变量名?

javascript - promise reject not working with mysql 错误

用于语法和内部错误的 JavaScript 事件监听器

angularjs - 在现有项目中更新 Ionic

node.js - 使用 NodeJS Promise 查询 MongoDB

C 程序 - 取消引用指针

Java - 从 1 个输入流读取字节和字符串

javascript - 使用 Json_encode 将 PHP 数组传递给 Javascript

javascript - 使用 jquery 选择器追加元素