简体   繁体   English

检查所有数组项是否都未定义或为空字符串

[英]Check if all of array items are undefined or empty string

How to check if all of items are undefined or empty string '' ? 如何检查是否所有的items都是undefined或空字符串''

var items = [variable_1, variable_2, variable_3];

Is there any nice way to do that instead of big if ? 有没有什么好的办法做到这一点,而不是大的if Not ES6. 不是ES6。

You can use every : 您可以使用every

The every() method tests whether all elements in the array pass the test implemented by the provided function. every()方法测试数组中的所有元素是否通过提供的函数实现的测试。 It returns a Boolean value. 它返回一个布尔值。

一个使用Array.prototype.some来查找至少一个不是undefined或''的元素的内衬,如果找到一个,则返回true

!items.some(item => item != undefined || item != '')

Here's another one I just thought of: 这是我刚刚想到的另一个:

if (array.join("") === "") 
  // all undefined or ""

Note that that'll also be true if an element is null , not undefined , so it may or may not suit the OP. 请注意,如果元素为null ,而不是undefined ,这也将true ,因此它可能适合或可能不适合OP。 Advantage is that it doesn't need a callback function. 优点是它不需要回调函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM