从 JavaScript 数组中删除空值
我有一个 javascript 数组。
addresses = new Array(document.client.cli_Build.value,
document.client.cli_Address.value,
document.client.cli_City.value,
document.client.cli_State.value,
document.client.cli_Postcode.value,
document.client.cli_Country.value);
document.client.cli_PostalAddress.value = addresses.join(", ");
我必须将所有这些数组值的内容复制到邮政地址文本区域。当我使用上面的连接函数时,为空值添加了逗号。如何删除这个多余的逗号?
谢谢
I am having a javascript array.
addresses = new Array(document.client.cli_Build.value,
document.client.cli_Address.value,
document.client.cli_City.value,
document.client.cli_State.value,
document.client.cli_Postcode.value,
document.client.cli_Country.value);
document.client.cli_PostalAddress.value = addresses.join(", ");
I have to copy the content of all these array value to the postal address textarea. when i use the above join function, comma has been added for null values. How to remove this extra commas?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您可以使用
filter
进行过滤输出 null 值:You can use
filter
to filter out the null values:使用
过滤器
删除所有 falsy 值的方法:Use
filter
method to remove all falsy values:另一种过滤器替代品
Another filter alternative
Underscore 是一个很好的实用程序库,用于函数式编程和列表操作:
编辑:还有一个更紧凑的方式(感谢安德鲁·德·安德拉德!):
Underscore is a nice utility library for functional programming and list manipulation:
Edit: And there is a more compact way (Thanks Andrew De Andrade!):
地址.filter(Boolean).join(", ")
addresses.filter(Boolean).join(", ")
或者应该是
??
Or should it be
??
还可以使用 Array.prototype.reduce() 。
它将数组减少为单个值,例如字符串。像这样:
a
保存中间结果,b
保存当前元素。One could also use Array.prototype.reduce().
It reduces an array to a single value, e.g. a string. Like so:
a
holds the intermediate result,b
holds the current element.如果你想消除所有的 undefined、null、NaN、""、0,一个简单的方法是使用过滤器回调函数和布尔函数的组合。
当您将值传递给布尔函数时,如果该值被省略或者为 0、-0、null、false、NaN、undefined 或空字符串 (""),则该对象的初始值为 false。
以下是此用法的示例:
以下是一些测试:
If you would like to eliminate all the undefined, null, NaN, "", 0, a simple way to do it is to use a combination of filter call back function and boolean function.
When you pass a value to the boolean function, if the value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.
Here is an example of this usage:
Here are some tests:
使用以下代码仅删除
null
值,其简短的 & simple:如果你想删除
null
,0
,false
&""
(空字符串)之类的值,然后使用:Use the following code to remove the
null
values only, its short & simple:If you want to remove
null
,0
,false
&""
(Empty String) like values, then use this: