2013-04-23 123 views
0

我曾看过以前的Q/A,但在那里找不到太多帮助。主要是因为我不明白什么是编码。从数组中删除空值 - javascript

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

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

我的代码 -

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,只是举行价值观,没有空字符串""应该在newArray。

预先感谢您。

+1

“如果颜色是空** **或者如果颜色是空字符串,将其包含在结果中“。没有值可以同时与'null'和'“”'相同。 – Jon 2013-04-23 08:42:15

+1

您使用||条件之间,所以如果颜色不是未定义的,你会插入它(只是例子)。使用&& – 2013-04-23 08:42:36

+0

哪些值应该为空或空?你在期待什么? – 2013-04-23 08:42:47

回答

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,,, 
+1

我想你的意思是'颜色[我]!== undefined'它不应该是'undefined',这将使它成为一个字符串 – shishirmk 2013-04-23 08:48:17

+0

是真的,我只是c/p代码,如果改变。我也在改变这一点。 – 2013-04-23 08:51:18

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]); 
    } 
} 

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

false 
0 
"" 
null 
undefined 
NaN 
1

您可以简单地使用颜色[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 type conversion

希望这会有所帮助。

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;}); 
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"]