在Javascript中从数组中删除空元素
如何在JavaScript中从数组中删除空元素在Javascript中从数组中删除空元素,javascript,arrays,Javascript,Arrays,如何在JavaScript中从数组中删除空元素 是否有一种简单的方法,或者我需要循环并手动删除它们?您可能会发现,与按照建议尝试循环和拼接相比,在阵列上循环并使用要保留在阵列中的项目构建新阵列更容易,因为在循环时修改数组的长度可能会带来问题 你可以这样做: function removeFalsyElementsFromArray(someArray) { var newArray = []; for(var index = 0; index < someArray.len
是否有一种简单的方法,或者我需要循环并手动删除它们?您可能会发现,与按照建议尝试循环和拼接相比,在阵列上循环并使用要保留在阵列中的项目构建新阵列更容易,因为在循环时修改数组的长度可能会带来问题 你可以这样做:
function removeFalsyElementsFromArray(someArray) {
var newArray = [];
for(var index = 0; index < someArray.length; index++) {
if(someArray[index]) {
newArray.push(someArray[index]);
}
}
return newArray;
}
函数removeFalsyElementsFromArray(someArray){
var newArray=[];
对于(var index=0;index
实际上,这里有一个更通用的解决方案:
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]
函数removeElementsFromArray(someArray,filter){
var newArray=[];
对于(var index=0;index
你明白了-你可以有其他类型的过滤函数。可能比你需要的要多,但我感觉很慷慨…;) 编辑:这个问题几乎在九年前得到了回答,当时
数组中没有多少有用的内置方法。prototype
现在,当然,我建议您使用filter
方法
请记住,此方法将返回一个新数组,其中的元素通过您提供给它的回调函数的条件
例如,如果要删除null
或未定义的值:
var数组=[0,1,null,2,”,3,未定义,3,,,,,,,4,4,5,6,,,,,];
var filtered=array.filter(函数(el){
返回el!=null;
});
console.log(过滤)代码>如果您拥有Javascript 1.6或更高版本,则可以使用一个简单的返回true
回调函数,例如:
arr = arr.filter(function() { return true; });
因为.filter
会自动跳过原始数组中缺少的元素
上面链接的MDN页面还包含一个不错的filter
错误检查版本,可以在不支持官方版本的JavaScript解释器中使用
请注意,这不会删除null
条目,也不会删除带有显式未定义的值的条目,但OP特别请求了“缺少”条目。这是可行的,我在中测试了它(您可以复制粘贴其IDE上的代码,然后按“重新加载”以查看其工作情况,无需创建帐户)
@阿尔尼塔克
实际上,如果添加一些额外的代码,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;
};
}
<代码> //这个原型是由Mozilla基金会提供的。
//是根据麻省理工学院许可证发行的。
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if(!Array.prototype.filter)
{
Array.prototype.filter=函数(fun/*,thisp*/)
{
var len=此长度;
如果(乐趣的类型!=“功能”)
抛出新的TypeError();
var res=新数组();
var thisp=参数[1];
对于(变量i=0;i
简单方法:
或-(仅适用于“文本”类型的单个数组项)
或-经典方式:简单迭代
var arr = [1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,],
len = arr.length, i;
for(i = 0; i < len; i++ )
arr[i] && arr.push(arr[i]); // copy non-empty values to the end of the array
arr.splice(0 , len); // cut the array and leave only the non-empty values
arr // [1,2,3,3,[],Object{},5,6]
更新-只是另一种快速、酷的方式(使用ES6):
删除空值
那么:
js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',')
1,2,3,3,0,4,4,5,6
这是一个干净的方法
var arr = [0,1,2,"Thomas","false",false,true,null,3,4,undefined,5,"end"];
arr = arr.filter(Boolean);
// [1, 2, "Thomas", "false", true, 3, 4, 5, "end"]
如果需要删除所有空值(“”、null、未定义和0):
要删除空值和换行符,请执行以下操作:
arr = arr.filter(function(e){ return e.replace(/(\r\n|\n|\r)/gm,"")});
例如:
arr = ["hello",0,"",null,undefined,1,100," "]
arr.filter(function(e){return e});
返回:
["hello", 1, 100, " "]
["hello", 0, 1, 100, " "]
更新(基于Alnitak的评论)
在某些情况下,您可能希望在数组中保留“0”并删除任何其他内容(null、undefined和“”),这是一种方法:
arr.filter(function(e){ return e === 0 || e });
返回:
["hello", 1, 100, " "]
["hello", 0, 1, 100, " "]
如果使用库是一个选项,我知道underline.js有一个名为compact()的函数,它还有其他几个与数组和集合相关的有用函数
以下是他们文档的摘录:
_.紧凑型(阵列)
返回已删除所有falsy值的数组副本。在JavaScript中,false、null、0、“、undefined和NaN都是false
_.compact([0,1,false,2',,3])
=>[1,2,3]
我只是简单地将我的声音添加到上面的“使用全局构造函数调用ES5的数组..filter()
”高尔夫技巧中,但我建议使用对象
,而不是上面建议的字符串
,布尔值
,或数字
具体来说,ES5的filter()
已经不会触发数组中未定义的元素;因此,一个普遍返回true
的函数,返回所有元素filter()
命中,必然只返回未定义的元素:
> [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
是function(){return true}arr = ["hello",0,"",null,undefined,1,100," "]
arr.filter(function(e){return e});
["hello", 1, 100, " "]
arr.filter(function(e){ return e === 0 || e });
["hello", 0, 1, 100, " "]
> [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]
> [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]
_.without(array, emptyVal, otherEmptyVal);
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
_.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], '');
--> ["foo", "bar", "baz", "foobar"]
[1, false, "", undefined, 2].filter(Boolean); // [1, 2]
_.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
// or even:
_.compact([1, false, "", undefined, 2]); // [1, 2]
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 } ) ;
foo = [0, 1, 2, "", , false, 3, "four", null]
foo.filter(function(e) {
return e === 0 ? '0' : e
})
[0, 1, 2, 3, "four"]
var stringObject = ["", "some string yay", "", "", "Other string yay"];
stringObject = stringObject.filter(function(n){ return n.length > 0});
["some string yay", "Other string yay"]
_.without(["text", "string", null, null, null, "text"], null)
// => ["text", "string", "text"]
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"]
// --- 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);
['a','b','',,,'w','b'].filter(v => v);
var data = [null, 1,2,3];
var r = data.filter(function(i){ return i != null; })
console.log(r)
var 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));
});
};
const array = [1, 32, 2, undefined, 3];
const newArray = array.filter(arr => arr);
var 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);
let newArr = arr.filter(e => e);
const arr = [1,2,3,undefined,4,5,6,undefined,7,8,undefined,undefined,0,9];
const clearArray = arr.filter( i => i );