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

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

问题描述

在某些情况下,我们可能会在数组结构中有 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 );

在这种情况下,这将完成工作,通常删除任何虚假值,我们会调用

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天全站免登陆