JavaScript数组推送缺失值

时间:2018-11-20 19:54:11

标签: javascript arrays for-loop

此函数将获取一个数组并将其分块为单独的数组,在开始处创建一个偏移量并将其包装在另一个数组中。我遇到的问题不是块中包括原始数组(arr1)中的所有数字。您可以在下面提供的链接中看到输出。它错过了数字5、13、21、29和30。有人能解释为什么会这样吗?

function chunkifyArray(input, chunkSize, offset) {

    const output = [];

    let tmp = offset ? new Array(offset).fill('') : [];

    for(var i = 0; i < input.length; i++){
        if (tmp.length < chunkSize) {
            tmp.push(input[i]);
        } else {
            output.push(tmp);
            tmp = [];     
        }
    }

    return output;
}

var arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30'];
console.log(chunkifyArray(arr1, 7, 3));

https://jsbin.com/zucaguvoti/edit?js,console

2 个答案:

答案 0 :(得分:2)

因为您从不推送这些值-您将tmp insead清空了……试试看:

deleteProfile = id => e => {
        ...
        .then(res => {
            if (res.code === 200) {
                const { onProfileDelete } = this.props
                onProfileDelete() // call prop func instead
            }
            console.log(res)
        })
}

进行编辑以确保将最后一个块压入输出...

答案 1 :(得分:0)

我对您的代码做了一些改动,以获得所需的结果。您可以使用%运算符,并记得在for循环的末尾添加最后一部分:

var data = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30'];

function chunkifyArray(input, chunkSize, offset=0) {
  let output = [], tmp = [];
  input = new Array(offset).fill('').concat(input);
  for (var i = 0; i < input.length; i++) {
    tmp.push(input[i])
    if (i && i%chunkSize == 0) {
        output.push(tmp);
	tmp = []
    }
  }
  output.push(tmp);  // add the remaining ones
  return output;
}

console.log(chunkifyArray(data, 7, 3));

您可以chunk带有 ES6 Array.reduce的阵列:

const data = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30']

const chunkBy = (arr, by=2, offset=0) => new Array(offset).fill('').concat(arr)
 .reduce((r,c,i) => (i%by==0 ? r.push([c]) : r[r.length-1] = [...r[r.length-1], c], r), [])
		
console.log(chunkBy(data, 7, 3))

如果不采用compact格式,则外观如下:

const data = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30']

const chunkBy = (arr, by=2, offset=0) => {
   arr = new Array(offset).fill('').concat(arr)
   return arr.reduce((r,c,i) => {
     if(i%by==0)
       r.push([c])
     else 
      r[r.length-1] = [...r[r.length-1], c]
     return r
   }, [])
}
		
console.log(chunkBy(data, 7, 3))