如何检查数组的所有元素是否为空?

编程入门 行业动态 更新时间:2024-10-27 04:34:32
本文介绍了如何检查数组的所有元素是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

除了使用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 (_pact(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.

更多推荐

如何检查数组的所有元素是否为空?

本文发布于:2023-11-30 00:27:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648115.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   为空   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!