如何从JavaScript数组中删除空元素?
有没有简单直接的方法,还是必须手动循环并逐个删除?
如何从JavaScript数组中删除空元素?
有没有简单直接的方法,还是必须手动循环并逐个删除?
使用 Underscore/Lodash:
一般用法:
_.without(array, emptyVal, otherEmptyVal);
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
带有空元素:
_.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], '');
--> ["foo", "bar", "baz", "foobar"]
请参阅 lodash文档中的without部分。
@Alnitak
实际上,如果您添加一些额外的代码,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;
};
}
鉴于其他人没有提到它,而且大多数人在其项目中都包含了下划线,您也可以使用_.without(array, *values);
。
_.without(["text", "string", null, null, null, "text"], null)
// => ["text", "string", "text"]
array.filter(Boolean);
const array = [
{ name: "tim", age: 1 },
undefined,
{ name: "ewrfer", age: 22 },
{ name: "3tf5gh", age: 56 },
null,
{ name: "kygm", age: 19 },
undefined,
];
console.log(array.filter(Boolean));
foo = [0, 1, 2, "", , false, 3, "four", null]
foo.filter(e => e === 0 ? true : e)
返回值
[0, 1, 2, 3, "four"]
如果您确定数组中不会有任何0,那么代码看起来会更好看一些:
foo.filter(e => e)
您可能会发现,通过循环数组并从中构建一个新的数组来保留所需项目比尝试循环和切割更容易,因为在循环过程中修改数组的长度可能会引入问题。
您可以像这样做:
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]
var arr = [0,1,2,"test","false",false,true,null,3,4,undefined,5,"end"];
arr.filter((v) => (!!(v)==true));
//output:
//[1, 2, "test", "false", true, 3, 4, 5, "end"]
const array = [1, 32, 2, undefined, 3];
const newArray = array.filter(arr => arr);
使用上面得到的最高投票答案中的第一个示例时,当字符串长度大于1时,我得到的是单个字符。以下是解决该问题的解决方案。
var stringObject = ["", "some string yay", "", "", "Other string yay"];
stringObject = stringObject.filter(function(n){ return n.length > 0});
如果未定义,则不返回,如果长度大于0,则返回。希望这能帮助到某些人。
返回值
["some string yay", "Other string yay"]
["", "some string yay", "", "", 123, "Other string yay"].filter(function(n){ return n.length > 0}) //gives your same result removing 123
将会得到相同的结果,并且会删除数字。把这个函数替换成 String,讽刺的是,数字会被留下,但在你给出的数组中会得到相同的结果。 - aamarks
var a = [,,]
和var a = [undefined, undefined]
之间存在区别。前者是真正的空数组,而后者实际上有两个键,但值为undefined
。 - Alnitaknull
/undefined
是更好的实践。例如,如果你的null
来自于使用map
函数映射另一个数组时,对于某些元素返回null
,那么在运行map
之前尝试使用Array.filter
过滤掉这些元素。这样可以使你的代码更易读/自我记录。显然,这并不适用于每种情况,但它可以应用于很多情况。 - Luke Redmore