如何检查字符串数组是否只包含空字符串

Lin*_* Vu 0 javascript typescript

我目前正在寻找一种解决方案,如何检查仅包含空字符串的字符串数组。有没有一种有效的方法来实现这种行为?

['', '', '', ''] // This should be true
['', null, null, ''] // This should be true
['a', '', '', ''] // This should be false
Run Code Online (Sandbox Code Playgroud)

Nin*_*olz 5

你需要一个环路,最好是有短路的。

const check = array => !array.some(Boolean);

console.log(check(['', '', '', '']));     //  true
console.log(check(['', null, null, ''])); //  true
console.log(check(['a', '', '', '']));    // false
Run Code Online (Sandbox Code Playgroud)


nim*_*sam 5

您可以使用一些功能:

let arr = ['', '', '', ''];
arr.some(Boolean);
Run Code Online (Sandbox Code Playgroud)

它将检查某些元素是否不是 false 值(''、0、null、undefined、false),如果全部为 false;它会返回 true。