如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
当前回答
您可能会发现,循环遍历数组并使用要从数组中保留的项构建新数组比按照建议进行循环和拼接更容易,因为在循环遍历时修改数组的长度可能会带来问题。
你可以这样做:
function removeFalsyElementsFromArray(someArray) {
var newArray = [];
for(var index = 0; index < someArray.length; index++) {
if(someArray[index]) {
newArray.push(someArray[index]);
}
}
return newArray;
}
实际上,这里有一个更通用的解决方案:
function removeElementsFromArray(someArray, filter) {
var newArray = [];
for(var index = 0; index < someArray.length; index++) {
if(filter(someArray[index]) == false) {
newArray.push(someArray[index]);
}
}
return newArray;
}
// then provide one or more filter functions that will
// filter out the elements based on some condition:
function isNullOrUndefined(item) {
return (item == null || typeof(item) == "undefined");
}
// then call the function like this:
var myArray = [1,2,,3,,3,,,,,,4,,4,,5,,6,,,,];
var results = removeElementsFromArray(myArray, isNullOrUndefined);
// results == [1,2,3,3,4,4,5,6]
你明白了——你可以有其他类型的过滤函数。可能比你需要的更多,但我感觉很慷慨…;)
其他回答
带下划线/Loddash:
一般使用情况:
_.without(array, emptyVal, otherEmptyVal);
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
有空:
_.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], '');
--> ["foo", "bar", "baz", "foobar"]
无需参阅lodash文档。
@阿尔尼塔克
实际上,如果您添加一些额外的代码,Array.filter可以在所有浏览器上运行。见下文。
var array = ["","one",0,"",null,0,1,2,4,"two"];
function isempty(x){
if(x!=="")
return true;
}
var res = array.filter(isempty);
document.writeln(res.toJSONString());
// gives: ["one",0,null,0,1,2,4,"two"]
这是您需要为IE添加的代码,但过滤器和函数式编程是值得的。
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
{
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
删除所有空元素
如果数组包含空对象、数组和字符串以及其他空元素,我们可以使用以下方法删除它们:
const arr=[[],['not','empty'],{},{key:'value'},0,1,null,2,“”,“here”,“”3,undefined,3,,,4,4,5,6,,]let filtered=JSON.stringify(arr.filter((obj)=>{回来[null,未定义,“”]。includes(obj)}).filter((el)=>{返回类型el!=“object”||对象.键(el).长度>0}))console.log(JSON.parse(已过滤))
简单压缩(从数组中删除空元素)
使用ES6:
常量arr=[0,1,null,2,“”,3,未定义,3,,,4,4,5,6,,]let filtered=arr.filter((obj)=>{return!〔null,undefined〕.includes(obj)})console.log(已过滤)
使用纯Javascript->
var arr=[0,1,null,2,“”,3,未定义,3,,,4,4,5,6,,]var filtered=arr.filter(函数(obj){return!〔null,undefined〕.includes(obj)})console.log(已过滤)
这样做怎么样
// Removes all falsy values
arr = arr.filter(function(array_val) { // creates an anonymous filter func
var x = Boolean(array_val); // checks if val is null
return x == true; // returns val to array if not null
});
简单ES6
['a','b','',,,'w','b'].filter(v => v);