如何从JavaScript数组中删除空元素?
有没有简单直接的方法,还是必须手动循环并逐个删除?
如何从JavaScript数组中删除空元素?
有没有简单直接的方法,还是必须手动循环并逐个删除?
var data = [null, 1,2,3];
var r = data.filter(function(i){ return i != null; })
console.log(r)
[1,2,3]
如果一个数组中包含空对象、数组和字符串,以及其他空元素,我们可以使用以下代码将它们删除:
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) => {
return ![null, undefined, ''].includes(obj)
}).filter((el) => {
return typeof el != "object" || Object.keys(el).length > 0
})
)
console.log(JSON.parse(filtered))
使用 ES6:
const arr = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , ,]
let filtered = arr.filter((obj) => { return ![null, undefined].includes(obj) })
console.log(filtered)
var arr = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , ,]
var filtered = arr.filter(function (obj) { return ![null, undefined].includes(obj) })
console.log(filtered)
in
运算符的过滤器。
let a = [1,,2,,,3];
let b = a.filter((x,i)=> i in a);
console.log({a,b});
let a=[]; a.abc=1
- 但通常没有人这样做(这是相当奇特的 - 因为您可以使用例如对象{}
而不是数组)。当您如此奇特地使用数组时,标准JS数组方法如map
、filter
等将忽略这些键值对 - 我的解决方案基于filter
并忽略它。很明显OP询问了标准JS数组(因为他没有提到这种奇特的用例)。 - Kamil Kiełczewskiin
运算符返回数组中的值。因此,我认为它只有在数组中的值与想要过滤的索引号相同时才起作用。但我现在看到 in
是指数组的属性(如索引),而不是值。 - Magne> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(function(){return true})
[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]
不过,写出...(function(){return true;})
比写...(Object)
要长一些;而且在任何情况下,Object
构造函数的返回值都会是某种对象。与上面建议使用的原始类型装箱构造函数不同,没有可能的对象值是falsey,因此在布尔设置中,Object
是function(){return true}
的简写。
> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(Object)
[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]
someArray.filter(String);
实际上等同于someArray.filter(function(x){ return String(x); });
。如果你希望删除所有假值,可以使用someArray.filter(Boolean);
来删除0、-0、NaN、false、''、null和undefined。 - robocatObject
构造函数与使用return true
方法相比的性能开销。@robocat提问者要求删除空元素,而不是null。 - Alnitak以上答案并不适用于所有类型。以下解决方案将删除null、undefined、{}
[]
、NaN
,并保留日期字符串,最好的是它甚至可以从嵌套对象中删除。
function removeNil(obj) {
// recursively remove null and undefined from nested object too.
return JSON.parse(JSON.stringify(obj), (k,v) => {
if(v === null || v === '') return undefined;
// convert date string to date.
if (typeof v === "string" && /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.test(v))
return new Date(v);
// remove empty array and object.
if(typeof v === 'object' && !Object.keys(v).length) return undefined;
return v;
});
}
function removeNil(obj) {
// recursively remove null and undefined from nested object too.
return JSON.parse(JSON.stringify(obj), (k,v) => {
if(v === null || v === '') return undefined;
// convert date string to date.
if (typeof v === "string" && /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.test(v))
return new Date(v);
// remove empty array and object.
if(typeof v === 'object' && !Object.keys(v).length) return undefined;
return v;
});
}
const ob = {
s: 'a',
b: 43,
countries: [ 'a', 'b', 'c' ],
l: null,
n: { ks: 'a', efe: null, ce: '' },
d: new Date(),
nan: NaN,
k: undefined,
emptyO: {},
emptyArr: [],
}
const output = removeNil(ob);
console.log(output);
console.log('Tests: ', ob.countries.length, typeof(ob.d))
那么这个怎么样:
js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',')
1,2,3,3,0,4,4,5,6
var removeNull = function() {
var nullCount = 0 ;
var length = this.length ;
for (var i=0, len=this.length; i<len; i++) { if (!this[i]) {nullCount++} }
// no item is null
if (!nullCount) { return this}
// all items are null
if (nullCount == length) { this.length = 0; return this }
// mix of null // non-null
var idest=0, isrc=length-1;
length -= nullCount ;
while (true) {
// find a non null (source) slot on the right
while (!this[isrc]) { isrc--; nullCount--; }
if (!nullCount) { break } // break if found all null
// find one null slot on the left (destination)
while ( this[idest]) { idest++ }
// perform copy
this[idest]=this[isrc];
if (!(--nullCount)) {break}
idest++; isrc --;
}
this.length=length;
return this;
};
Object.defineProperty(Array.prototype, 'removeNull',
{ value : removeNull, writable : true, configurable : true } ) ;
arr.filter(e => e)
。 - agm1984var data= {
myAction: function(array){
return array.filter(function(el){
return (el !== (undefined || null || ''));
}).join(" ");
}
};
var string = data.myAction(["I", "am","", "working", "", "on","", "nodejs", "" ]);
console.log(string);
输出:
我正在使用nodejs工作
它将从数组中删除空元素并显示其他元素。
“误用” for ... in (object-member) 循环。 => 只有真值出现在循环体中。
// --- Example ----------
var field = [];
field[0] = 'One';
field[1] = 1;
field[3] = true;
field[5] = 43.68;
field[7] = 'theLastElement';
// --- Example ----------
var originalLength;
// Store the length of the array.
originalLength = field.length;
for (var i in field) {
// Attach the truthy values upon the end of the array.
field.push(field[i]);
}
// Delete the original range within the array so that
// only the new elements are preserved.
field.splice(0, originalLength);
for ... in
的行为是从数组中删除未定义的键,但实际上您在此处没有其他代码来仅接受“真实”的值。 - Alnitakvar details = [
{
reference: 'ref-1',
description: 'desc-1',
price: 1
}, {
reference: '',
description: '',
price: ''
}, {
reference: 'ref-2',
description: 'desc-2',
price: 200
}, {
reference: 'ref-3',
description: 'desc-3',
price: 3
}, {
reference: '',
description: '',
price: ''
}
];
scope.removeEmptyDetails(details);
expect(details.length).toEqual(3);
scope.removeEmptyDetails = function(details){
_.remove(details, function(detail){
return (_.isEmpty(detail.reference) && _.isEmpty(detail.description) && _.isEmpty(detail.price));
});
};
var a = [,,]
和var a = [undefined, undefined]
之间存在区别。前者是真正的空数组,而后者实际上有两个键,但值为undefined
。 - Alnitaknull
/undefined
是更好的实践。例如,如果你的null
来自于使用map
函数映射另一个数组时,对于某些元素返回null
,那么在运行map
之前尝试使用Array.filter
过滤掉这些元素。这样可以使你的代码更易读/自我记录。显然,这并不适用于每种情况,但它可以应用于很多情况。 - Luke Redmore