简体   繁体   English

使用javascript删除无价值的数组项

[英]Removing array items with no value with javascript

I have a variable that looks like this: 我有一个看起来像这样的变量:

["something here", "", "something else here", ""]

As you can see there are a empty entries. 如您所见,其中有一个空条目。

I need to remove them so that the array contains no empty entries. 我需要删除它们,以便数组不包含任何空条目。

How can I do this? 我怎样才能做到这一点?

You can use the Array filter method. 您可以使用数组过滤器方法。 filter(Boolean) filters all falsy items. filter(Boolean)过滤所有虚假项目。

['',null,0,1].filter(Boolean) // [1]

 const arr = ["something here", "", "something else here", ""]; const newArr = arr.filter(Boolean); console.log(newArr); 

You can use filter() and check length of string 您可以使用filter()并检查string length

 let arr =["something here", "", "something else here", ""]; console.log(arr.filter(a => a.length)) 

Use the following code 使用以下代码

let array ="something here", "", "something else here", ""];
array.forEach((item,index)=>{
    if(item===""){
        array.splice(index,1);
    }
});

There is a method in JavaScript called filter . JavaScript中有一种称为filter的方法。 This method is responsible to literally filter which values you want (or not). 此方法负责从字面上筛选所需(或不需要)的值。

In this case, maybe you can use the following approach: 在这种情况下,也许您可​​以使用以下方法:

var filtered = ["something here", "", "something else here", ""].filter(function(item) {
   return item != "";
});

The filtered variable will have the result: 过滤后的变量将具有以下结果:

["something here", "something else here"]

One last option, similar to the Boolean one, is a basic filter returning the element if the element is not null, but I personnaly find it more explicit than Boolean: 最后一个选项与布尔值类似,是一个基本过滤器,如果元素不为null,则返回该元素,但我个人认为它比布尔值更明确:

 let array = ['hi', 'this', '', 'is', 'a', '', 'demo']
 let filteredArray = array.filter(str => str)
// filteredArray will be equal to ['hi', 'this', 'is', 'a', 'demo']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM