从数组中删除未定义的值 [英] Removing undefined values from Array

查看:235
本文介绍了从数组中删除未定义的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,可能会在数组结构中出现undefined或通常为 falsy 的值.例如,当从一些未知来​​源(例如数据库或HTML结构)读取和填充数据时.喜欢

In certain situations, it may happen that we have undefined or generally falsy values in Array structures. For instance when reading and filling data from some unknown sources like Databases or HTML structures. Like

var data = [42, 21, undefined, 50, 40, undefined, 9]

由于在循环访问此类数组和处理元素时可能会引起麻烦,因此删除undefined(虚假值)的最佳实践是什么?

Since that might cause trouble when looping over such arrays and working on the elements, what is the best practice to remove undefined (falsy values) ?

推荐答案

在这里使用Array.prototype.filter可能很明显.因此,要删除仅未定义的值,我们可以调用

To use Array.prototype.filter here might be obvious. So to remove only undefined values we could call

var data = [42, 21, undefined, 50, 40, undefined, 9];

data = data.filter(function( element ) {
   return element !== undefined;
});

如果要过滤掉所有虚假值(例如0或null),可以改用return !!element;.

If we want to filter out all the falsy values (such as 0 or null) we can use return !!element; instead.

但是,只要将Boolean构造函数或Number构造函数分别传递给.filter:

But we can do it slighty more elegant, by just passing the Boolean constructor function, respectively the Number constructor function to .filter:

data = data.filter( Number );

在这种情况下,这样做就可以了,一般来说,要删除任何 falsy 值,我们会调用

That would do the job in this instance, to generally remove any falsy value, we would call

data = data.filter( Boolean );


由于Boolean()构造函数在 truthy 值上返回true并且在任何 falsy 值上返回false,所以这是一个非常简洁的选项.


Since the Boolean() constructor returns true on truthy values and false on any falsy value, this is a very neat option.

这篇关于从数组中删除未定义的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆