JavaScript - Check if at least one variable is true

Wer*_*rl_ 2 javascript variables boolean

How do I check if at least 1 out of a group of variables is true. For example:

var v1 = false;
var v2 = false;
var v3 = false;
var v4 = false;
var v5 = false;
Run Code Online (Sandbox Code Playgroud)

Let's say that I have 5 buttons and the variable of v1 changes every time I click on button1 and so on. Let's suppose that I click on button4 and v4 changes to true. How do I check if at least one of the 5 variables is true. Something like this:

if(1/5 variables is true) {do something}
Run Code Online (Sandbox Code Playgroud)

Should I create an array or something?

Ale*_*lex 13

if([v1, v2, v3, v4, v5].some(item => item)) {
    //code
}
Run Code Online (Sandbox Code Playgroud)


use*_*738 5

This is conditional OR operation:

if (v1 || v2 || v3 || v4 || v5) { do something }
Run Code Online (Sandbox Code Playgroud)

这是这方面最简单的解决方案。但.some()也比较棘手,但也是很好的方法。一探究竟。

如果它是 100 个元素,你不能写(v1 || v2 ...|| v100),那么使用.some()会有所帮助。

例子:

if (v1 || v2 || v3 || v4 || v5) { do something }
Run Code Online (Sandbox Code Playgroud)