Reputation: 13
How can i write many "OR" in one "IF" javascript? This code is wrong:
if (d.getMinutes().toString() == 1 || 21 || 31 || 41 || 51){
Something happen
}
Upvotes: 1
Views: 66
Reputation: 54223
In your specific case, you could simply the modulo operator:
if (d.getMinutes() % 10 == 1){
// Something happens
}
since every minute value that you listed ends with 1
, and you listed all the possible values ending with 1
.
Upvotes: 0
Reputation: 1
This is something I did for a project that you might find useful. This applies with user input, but I'm also sure it could be transformed to match what it is you're doing! try using "else if" instead of "or" for multiple options.
function yourFunction(str) {
len = str.length;
mod = len % 4;
if (mod === 0) {
return "Option 1"
}
else if (mod === 1) {
return "Option 2"
}
else if (mod === 2) {
return "Option 3"
}
else if (mod === 3) {
return "Option 4"
}
}
Upvotes: 0
Reputation: 816
Another way of doing the same with cleaner code (you don't need toString
here):
var d = new Date(2010, 1, 1, 10, 21, 0);
if ([1, 21, 31, 41, 51].includes(d.getMinutes())) {
// do something
console.log("21 minutes");
}
var d2 = new Date(2010, 1, 1, 10, 25, 0);
if ([1, 21, 31, 41, 51].includes(d2.getMinutes())) {
// do something
console.log("This is not executed");
}
Upvotes: 0
Reputation: 3820
You can transform your problem to something like this
Store the values you want to compare in array
and pass into includes() the original value to achieve that.
if ([1,21,31,41,51].includes(d.getMinutes())){
Something happen
}
Upvotes: 1
Reputation: 471
You could do:
if ([1, 21, 31, 41, 51].indexOf(d.getMinutes()) !== -1){
Something happen
}
The toString would not help because the array are numbers
There might be better solutions though.
Upvotes: 0
Reputation: 927
let dMinutes = d.getMinutes().toString();
if ( dMinutes == 1 || dMinutes == 21 || dMinutes == 31 || dMinutes == 41 || dMinutes == 51 ) {
Something happen
}
Upvotes: 0
Reputation: 22683
If you don't want to repeat d.getMinutes().toString()
in your if
, it's common approach to use an array and includes()
for that purpose:
if ([1, 21, 31, 41, 51].includes(d.getMinutes()) {
Note that toString()
is redundant in this case.
Upvotes: 1
Reputation: 2162
In Javascript, each individual condition must evaluate to a boolean.
var dMinutes = d.getMinutes().toString();
if (dMinutes == 1 || dMinutes == 21 || dMinutes == 31 || dMinutes == 41 || dMinutes == 51){
Something happen
}
Upvotes: 1