删除数组中的空双引号元素,同时保留其他元素
Posted
技术标签:
【中文标题】删除数组中的空双引号元素,同时保留其他元素【英文标题】:remove empty double quote elements inside an array while leaving other elements 【发布时间】:2020-07-23 21:24:40 【问题描述】:我正在尝试删除数组中的双引号,数组如下所示。
let array: string[] = ["apple"," ","orange"," ","grape","art"," "," "]
【问题讨论】:
然后呢? javascript没有裸词。字符串需要有引号,否则你的代码将无法工作 只删除空的双引号。 请在问题中相应指定。您可以使用过滤器功能为developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 【参考方案1】:一个不好回答的问题!但只是为了你的知识。这甚至可以处理undefined
。
let array = ["apple", " ", "orange", " ", "grape", "art", " ", " "];
let filtered = ["apple", " ", "orange", " ", "grape", "art", " ", " ", undefined].filter((x ="") => x.trim())
console.log(filtered)
【讨论】:
【参考方案2】:const array = ["apple"," ","orange"," ","grape","art"," "," "];
array.filter(element => element.trim());
【讨论】:
请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常质量更高,更有可能吸引投票。【参考方案3】: let array: string[] = ["apple"," ","orange"," ","grape","art"," "," "]
let result = array.filter(function(item,pos,self)
return item.length > 1;
)
console.log(result)
【讨论】:
以上是关于删除数组中的空双引号元素,同时保留其他元素的主要内容,如果未能解决你的问题,请参考以下文章
如何删除单引号并将双引号放在javascript中的对象数组中[关闭]