如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
当前回答
这只会删除空值,而不是虚假值,我认为这是更可取的。
也可以选择删除空值。
这种方法应该比使用拼接快得多。
function cleanArray(a, removeNull) {
var i, l, temp = [];
l = a.length;
if (removeNull) {
for (i = 0; i < l; i++) {
if (a[i] !== undefined && a[i] !== null) {
temp.push(a[i]);
}
}
} else {
for (i = 0; i < l; i++) {
if (a[i] !== undefined) {
temp.push(a[i]);
}
}
}
a.length = 0;
l = temp.length;
for (i = 0; i < l; i++) {
a[i] = temp[i];
}
temp.length = 0;
return a;
}
var myArray = [1, 2, , 3, , 3, , , 0, , null, false, , NaN, '', 4, , 4, , 5, , 6, , , , ];
cleanArray(myArray);
myArray;
其他回答
var a = [{a1: 1, children: [{a1: 2}, undefined, {a1: 3}]}, undefined, {a1: 5}, undefined, {a1: 6}]
function removeNilItemInArray(arr) {
if (!arr || !arr.length) return;
for (let i = 0; i < arr.length; i++) {
if (!arr[i]) {
arr.splice(i , 1);
continue;
}
removeNilItemInArray(arr[i].children);
}
}
var b = a;
removeNilItemInArray(a);
// Always keep this memory zone
console.log(b);
美好的很不错的我们也可以像这样替换所有数组值
Array.prototype.ReplaceAllValues = function(OldValue,newValue)
{
for( var i = 0; i < this.length; i++ )
{
if( this[i] == OldValue )
{
this[i] = newValue;
}
}
};
var data = [null, 1,2,3];
var r = data.filter(function(i){ return i != null; })
console.log(r)
[1,2,3]
由于没有其他人提到它,而且大多数人的项目中都包含下划线,因此您也可以使用_.without(array,*values);。
_.without(["text", "string", null, null, null, "text"], null)
// => ["text", "string", "text"]
@阿尔尼塔克
实际上,如果您添加一些额外的代码,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;
};
}