如何在js中删除数组的最后一个元素

时间:2018-01-22 22:32:14

标签: javascript arrays

我有一个二维数组,其中最后一个元素是空的。 像这样:

data = [["1","2","3","","",""],["4","5","6","x","f",""],["7","8","9","",""]]

现在我想删除空元素并使用.length

获取正确的新大小

我尝试过这样但不起作用:

        for (i = 0; i != data[2].length-1; i++) {
            if (data[2][i].isEmpty()) {
                data[2] = data[2].splice(i, 1);
            }
        }

有什么好的解决方案吗?

5 个答案:

答案 0 :(得分:6)

您可以在使用Boolean作为回调进行过滤后映射数组,以保留truthy元素。

var data = [["1", "2", "3", "", "", ""], ["4", "5", "6", "x", "f", ""], ["7", "8", "9", "", ""]];

data = data.map(a => a.filter(Boolean));

console.log(data);

答案 1 :(得分:2)

由于更改了数组的长度,for()循环中的拼接很棘手

使用map()filter()

let data = [["1","2","3","","",""],["4","5","6","x","f",""],["7","8","9","",""]]

data = data.map(arr => arr.filter(e => e.trim()));  

console.log(JSON.stringify(data))

答案 2 :(得分:1)

使用.map.filter

const data = [
  ['1', '2', '3', '', '', ''],
  ['4', '5', '6', 'x', 'f', ''],
  ['7', '8', '9', '', ''],
];

const cleanData = data.map(arr => arr.filter(value => value || false));

console.log(cleanData);

答案 3 :(得分:0)

箭头功能很优雅,但目前还不完全支持,所以可能以下可能是更好的解决方案:

const data = [
    ['1', '2', '3', '', '', ''],
    ['4', '5', '6', 'x', 'f', ''],
    ['7', '8', '9', '', ''],
];

const filteredData = data.map(function (arr) {
    return arr.filter(Boolean);
});


console.log(filteredData);

答案 4 :(得分:0)

var data = [["1","2","3","","",""],["4","5","6","x","f",""],["7","8","9","",""]];
var i;

for(i = 0; i < data[2].length; i++){
  if(data[2][i] == '')
  {
    var temp = data[2].slice(0,i);
    break;
  }
}

console.log(temp);

如果你想保持相同的数据结构和每个数组最后会有一系列空字符串的模式,这将找到第一个空字符串并切断其余字符串。