0

我查看了以前的 Q/A 并没有找到太多帮助。主要是因为我不明白编码的内容。

我只是想删除数组中的任何空值。

我的简单方法 - 那行不通!

我的代码是 -

var colors = [a, b, c, d, e, f];
var newArray = [];
for (var i = 0; i < colors.length; i++) {
  if (colors[i] !== 'undefined' || colors[i] !== null || colors[i] !== "") {
    newArray.push(colors[i]);
  }
}
console.log(newArray.length); // == 6 
console.log(newArray) //== yellow,blue,red,,,

我会认为我的 if 语句将过滤所有具有值的元素并推送到我的新数组。我真的需要 newArray 长度等于 3 并且只保留 vales,""newArray 中不应该有空字符串。

先感谢您。

4

5 回答 5

4

使用 && 代替 ||:

var colors = ["yellow", "","red", "blue", "", ""];
var newArray = [];
for (var i = 0; i < colors.length; i++) {
  if (colors[i] !== undefined && colors[i] !== null && colors[i] !== "") {
    newArray.push(colors[i]);
  }
 }
console.log(newArray.length); // == 3 
console.log(newArray) //== yellow,blue,red,,, 
于 2013-04-23T08:45:46.933 回答
2

使用 && 代替 ||:

var colors = ["yellow", "","red", "blue", "", ""];
var newArray = [];
for (var i = 0; i < colors.length; i++) {
  if (colors[i] !== undefined && colors[i] !== null && colors[i] !== "") {
    newArray.push(colors[i]);
  }
 }
console.log(newArray.length); // == 3 
console.log(newArray) //== yellow,blue,red,,, 

对于您的用例,您还可以使用

for (var i = 0; i < colors.length; i++) {
  if (colors[i]) {
    newArray.push(colors[i]);
  }
 }

这将过滤掉任何虚假值。虚假值包括

false
0
""
null
undefined
NaN
于 2013-04-23T08:54:57.463 回答
1

您可以简单地使用 colors[i] 进行存在检查,

var colors = ["yellow", "","red", "blue", "", "", true, 1];
var newArray = [];
for (var i = 0; i < colors.length; i++) {
    if (typeof colors[i] == 'string' && colors[i]) {
        newArray.push(colors[i]);
    }
}
console.log(newArray) //["yellow", "red", "blue"]

相关资源javascript类型转换

希望这可以帮助。

于 2013-04-23T09:02:18.977 回答
0

如果“假”值很重要,那么:

var colors = [0,1,'a',,'',null,undefined,false,true];
    colors = colors.filter(function(e){
        return (e===undefined||e===null||e==='')?false:~e;
    });

别的:

var colors = [0,1,'a',,'',null,undefined,false,true];
        colors = colors.filter(function(e){return e;});
于 2013-04-23T09:31:44.920 回答
0
var colors = ["yellow", null, "blue", "red", undefined, 0, ""];

// es5:
var newArray = colors.filter(function(e){return !!e;});

// es6:
var newArray = colors.filter((e)=>!!e);

console.log(newArray.length); // ==> 3
console.log(newArray) // ==> ["yellow","blue","red"]
于 2016-06-01T15:00:25.087 回答