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));
// };
});
答案 0 :(得分:0)
您必须为此使用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));
// };
});
答案 1 :(得分:0)
您将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);
}
答案 2 :(得分:0)
我想您只想打印所有内容一次,如果是这种情况,则必须每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])
}
})