admin管理员组文章数量:1193748
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;
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}
Should I create an array or something?
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;
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}
Should I create an array or something?
Share Improve this question asked May 8, 2017 at 15:19 Werl_Werl_ 2333 gold badges4 silver badges10 bronze badges 3 |4 Answers
Reset to default 15if([v1, v2, v3, v4, v5].some(item => item)) {
//code
}
This is conditional OR
operation:
if (v1 || v2 || v3 || v4 || v5) { do something }
This is the easiest solution on this regard. But .some()
is trickier but good way to do also. Check it out.
If it is 100 elements you can't write (v1 || v2 ...|| v100)
so then using .some()
will help.
Example:
function isTrue(element, index, array) {
return element;
}
if ([2, 5, 8, 1, 4].some(isTrue)) { do something; }
Method #1: You can apply multiple variables to a single var using commas but if you really need the separation then use that instead.
var v1,v2,v3,v4,v5 = false;
if (v1 || v2 || v3 || v4 || v5)
{
//code to be executed
}
Write or condition in your if statement.
if( v1 || v2 || v3 || v4 || v5)
{
// Do something
}
本文标签: JavaScriptCheck if at least one variable is trueStack Overflow
版权声明:本文标题:JavaScript - Check if at least one variable is true - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738435159a2086632.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
v1 || v2 || v3 || v4 || v5
– Rayon Commented May 8, 2017 at 15:20