如何删除数组内的数组的最后一项

时间:2016-08-24 00:30:35

标签: javascript arrays

如何删除数组中数组的最后一项。在这种情况下,我想删除数组内部数组末尾的null。这是我的代码

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var arrWithSubArr = [];

  for(var i = 0; i < arr.length / size; i++){
    arrWithSubArr.push([]);
  }
  var index = 0;
  var whichSubArr = 0;
  for(whichSubArr = 0; whichSubArr < arr.length / size; whichSubArr++){
    for(i = 0; i < size; index++){
      arrWithSubArr[whichSubArr].push(arr[index]);
      i++;
    }
  }

  return arrWithSubArr;
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4);

3 个答案:

答案 0 :(得分:1)

我相信你的最终目标是将原始数组拆分为多个数组,每个数组等于或小于指定的大小(在最后一个子数组不等于size的情况下)。

可以更容易地防止它们被插入,而不是删除在循环中添加的未定义值
function chunkArrayInGroups(arr, size) {
  // Break it up.
  var arrWithSubArr = [];

  var whichSubArr = 0;

  // Using Math.ceil returns the smallest integer greater than or equal to the number
  // In this case your minimum number of sub arrays needed to contain all the items of the original array
  var numOfSubArrs = Math.ceil(arr.length/size);

  // create the empty sub arrays
  for(var i = 0; i < numOfSubArrs; i++){
    arrWithSubArr.push([]);
  }

  for (var i =0; i < arr.length; i++) {
      arrWithSubArr[whichSubArr].push(arr[i]);
      // starting with the inital sub array at position 0
      // increment to the next sub array once the current one is equal to the specified size
      if (arrWithSubArr[whichSubArr].length == size){
          whichSubArr++;
      }
  }

  return arrWithSubArr;
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4);

答案 1 :(得分:0)

只是数组lengthlength - 1

答案 2 :(得分:0)

删除数组中的最后一项并更改原始数组。我会用

/my-project-name
    /my-project-name
        server.py
        settings.py
        urls.py
        wsgi.py
    ...
    /static
    /static_resources
    manage.py