[英]Remove empty values from array simply - 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中不应包含任何空字符串""
。
先感谢您。
使用&&代替||:
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,,,
使用&&代替||:
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
您可以简单地使用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类型转换
希望这可以帮助。
如果“假”值很重要,则:
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;});
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"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.