【问题标题】:each time printing result set in data of 3每次打印结果集在 3 个数据中
【发布时间】:2019-12-23 15:47:06
【问题描述】:
  • 我正在尝试以三个为一组打印数据。
  • 所以我想我会迭代数组,每次我都会获取三个元素并打印它。
  • 所以我想我会使用 slice 但不工作
  • 但我不知道如何继续。
  • 在下面提供我的代码 sn-p。
  • 我已调试但仍不确定如何继续。
let array = [1, 4, 5, 6, 7, 78, 3, 999, 544, 3, 3, 32233, 223, ];
array.map(search => {
  //  return {
  console.log("chunks of data--->", search.slice(3));
  //     };
});

【问题讨论】:

  • 预期输出是什么?

标签: javascript html arrays ecmascript-6 iteration


【解决方案1】:

您必须为此使用index

let array = [1, 4, 5, 6, 7, 78, 3, 999, 544, 3, 3, 32233, 223, ];
array.map((search,index) => {

  if(index%3!==0){
     return;
  }

  let limit = index+3;
  
  // this part need when index almost at the end of the array
  if((index+3)>=array.length){
     limit =array.length;
  }
  console.log("chunks of data--->", array.slice(index,limit));
  //     };
});

【讨论】:

  • 嘿,谢谢,它成功了,但你能不能给 cmets。我无法理解这一行const limit = (index+3)>=array.length?array.length:index+3;,以便我可以学习
  • @tkkk 我的代码改动不大,现在一定很容易理解
  • 嘿,如果我删除下面的 if 条件也可以正常工作,为什么我最后没有看到空格字符 ` if((index+3)>=array.length){ limit =array 。长度; }`
  • 你能不能给我一些更详细的解释
  • @tkkk,没有条件它不能正常工作1 4 54 5 6 包含相同的元素。所以关于细节,我不觉得很难理解,只是运营商+ - = < >conditions。你很难理解哪一部分?
【解决方案2】:

我认为您只想打印一次所有内容,如果是这种情况,您必须使用 %3 每 3 次执行一次操作 - 在这种情况下,记录当前和过去的 2 个元素。最后,您还必须打印剩余的元素,以防您的元素数量不是 3 的倍数。

// a forEach loop takes an array and calls a function on each element in it
array.forEach((el, index, arr) => {
    // is this element a multiple of 3?
    if ((index + 1) % 3 === 0) {
        // If so, log it, as well as the 2 preceding elements
        console.log(arr[index-2], arr[index-1], el)

    // Otherwise, is this element the last one in the array, meaning there
    // wont be another tuple logging this element
    } else if (index === arr.length - 1) {
        // If so, how many elements are left, one or two?
        // log this many last elements to the console
        // I used a ternary in this case it is basically a shorthand if 
        // [expression] ? [if true] : [if false]
        arr.length % 3 === 1 ? console.log(arr[index]) : console.log(arr[index - 1], arr[index])
    }
})

【讨论】:

  • 嘿,谢谢,它起作用了,但你能不能给 cmets。我无法理解这一行arr.length % 3 === 1 ? console.log(arr[index]) : console.log(arr[index - 1], arr[index]),以便我可以学习
【解决方案3】:

您将slice 与数组而不是数字一起使用,以获取3(或任意n)的块,请使用:

var array = [1, 4, 5, 6, 7, 78, 3, 999, 544, 3, 3, 32233, 223, ];

var n = 3;
var chunk;

for (var i = 0; i < array.length; i += n) {
  chunk = array.slice(i, i + n);
  console.log(chunk);
}

【讨论】:

  • 嘿,谢谢,它起作用了,但你能不能给 cmets。我无法理解这一行var i = 0; i &lt; array.length; i += n),所以我可以学习
猜你喜欢
  • 2017-11-27
  • 2013-08-14
  • 2013-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多