如何检查数组的所有元素是否为空? [英] How do I check if all elements of an array are null?

查看:967
本文介绍了如何检查数组的所有元素是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了使用Lodash之外,检查具有所有空值的数组的最佳方法是什么,可能还有ES6?

What's the best way to check for an array with all null values besides using Lodash, possibly with ES6?

var emp = [null, null, null];
if (_.compact(emp).length == 0) {
  ...
}


推荐答案

附注:您的解决方案实际上并未检查全零数组。它只是检查一个全假的数组。 [0,false,''] 仍会通过支票。

A side note: Your solution doesn't actually check for an all-null array. It just checks for an all-falsey array. [0, false, ''] would still pass the check.

您可以使用 Array#every 方法检查数组的每个元素是否满足特定条件:

You could use the Array#every method to check that every element of an array meets a certain condition:

const arr = [null, null, null];
console.log(arr.every(element => element === null));

每个接受第一个回调参数是迭代的当前元素。如果元素为null,则回调返回true,否则返回false。如果,对于所有元素,回调返回true,它将计算为true,因此如果数组中的所有元素都为null,则为真。

every takes a callback in which the first argument is the current element being iterated over. The callback returns true if the element is null, and false if it is not. If, for all the elements, the callback returns true, it will evaluate to true, thus if all elements in the array are null, it's true.

这篇关于如何检查数组的所有元素是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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