【问题标题】:How to iterate through an array which contain less than the iterator value如何遍历包含小于迭代器值的数组
【发布时间】:2021-06-12 19:55:09
【问题描述】:

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

   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 长度希望这足够清楚

【问题讨论】:

    标签: javascript node.js arrays for-loop iteration


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 2014-06-30
      相关资源
      最近更新 更多