首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >每次打印结果集的数据为3

每次打印结果集的数据为3
EN

Stack Overflow用户
提问于 2019-08-17 19:58:32
回答 3查看 52关注 0票数 0
  • 我正试着把数据打印成三块。
  • 所以我想我会迭代这个数组,每次我会拿出三个元素并打印出来。
  • 所以我想我会用切片但不起作用
  • 但我不知道该如何进行。
  • 提供下面的代码片段。
  • 我调试了一下,但还是不知道该怎么做。
代码语言:javascript
复制
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));
  //     };
});
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-08-17 20:14:48

我认为您只想打印所有东西一次,如果是这样,您必须使用%3来做某事每3x时间-在本例中记录当前和过去的2个元素。最后,您还必须打印剩余的元素,以防您的元素数不是3的倍数。

代码语言:javascript
复制
// 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])
    }
})
票数 0
EN

Stack Overflow用户

发布于 2019-08-17 20:05:36

为此,必须使用index

代码语言:javascript
复制
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));
  //     };
});

票数 0
EN

Stack Overflow用户

发布于 2019-08-17 20:09:36

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

代码语言:javascript
复制
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);
}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57539533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档