How can i write many "OR" in one "IF" javascript - javascript

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
}

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
}

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
}

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.

let dMinutes = d.getMinutes().toString();
if ( dMinutes == 1 || dMinutes == 21 || dMinutes == 31 || dMinutes == 41 || dMinutes == 51 ) {
Something happen
}

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.

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");
}

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"
}
}

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.

Related

loop that count to 100 and replace with some text any number that divide by 3 or conatins number 3

function checker (num){
for(i = 1; i <= num; ++i){
if(i % 3 === 0 ||
i === 13 ||
i === 23 ||
i === 33 ||
i === 43 ||
i === 53 ||
i === 63 ||
i === 73 ||
i === 83 ||
i === 93){
console.log('boom')
}
else{
console.log(i)
}
}
}
checker(100)
so i made this , but thats looks ugly , how to do it correct ? like any number that contains 3 replace it with some text. thank you.
You could check the string, too.
if (i % 3 === 0 || i.toString().includes('3')) ...
If your loop only counts to 100, you only need to check the tens and ones place to determine if it's a 3. You can use the JavaScript modulo operator % and the Math.floor() static method:
if (Math.floor(i / 10) === 3 || i % 10 === 3 || i % 3 === 0) // ...
The Math.floor method will return true if dividing the number by 10 and rounding down returns 3 (true for the numbers 30 to 39 inclusive), and the % modulo operator will return true when dividing i by 10 has a remainder of 3 (true for 3, 13, 23, 33, etc.) i % 3 === 0 is from your original function.

Checking MomentJS data toString not evaluating properly in if check

I am trying to create a function to create an array of the next two weeks of days that are not Friday, Saturday, or Sunday. moment().isoWeekday().toString() returns a number 1-7 depending on the day. I have an if statement checking to see if each day matches 5, 6, or 7, but they all return true no matter the day. I'm not sure what I'm doing wrong. Please advise.
for (let i = 1; i < 14; i++) {
if (moment().add(i, 'days').isoWeekday().toString() !== '5' ||
moment().add(i, 'days').isoWeekday().toString() !== '6' ||
moment().add(i, 'days').isoWeekday().toString() !== '7') {
console.log(moment().add(i, 'days').isoWeekday().toString())
dayArray.push(moment().add(i, 'days').toString());
}
}
The error seems to come from you condition, you use OR (||) instead AND (&&)
for (let i = 1; i < 14; i++) {
if (moment().add(i, 'days').isoWeekday().toString() !== '5' &&
moment().add(i, 'days').isoWeekday().toString() !== '6' &&
moment().add(i, 'days').isoWeekday().toString() !== '7') {
console.log(moment().add(i, 'days').isoWeekday().toString())
dayArray.push(moment().add(i, 'days').toString());
}
}

Simple javascript if statement with charAt is not working

Its simple, if a user enters a number that does not beggin with 6 or 9, he gets error:
console.log($(this).val().charAt(0));
if($(this).val().charAt(0) != 6 || $(this).val().charAt(0) != 9){
x=false;
}else {
x=true;
}
Console.log correctly displays the first character.. that means the value exists..
But no matter if I type 6 or 7 or 9, i will always get false... Why?
Whatever the value of somevar,
somevar!=6 OR somevar!=9
is always true.
The best solution here would probably be a regular expression:
var x = /^[69]/.test($(this).val());
You need to invert the logic conditions as both states cannot possibly be true at the same time, so x is always set to false. Try this:
var chr = $(this).val().charAt(0);
if (chr == '6' || chr == '9') {
x = true;
} else {
x = false;
}
From there you can now see that you don't even need the if condition as you can set x directly, like this:
var chr = $(this).val().charAt(0);
var x = chr == '6' || chr == '9';

Please help to find out why the code works in such manner (JavaScript)

i've been working on a primitive code and got the unexpected result.
var one = prompt("Enter the number", "4");
var age = parseInt(one);
if (age >= 14 || age <= 90) {
console.log("Correct");
} else {
console.log("Wrong")
}
When I put 100, for example, it says "Correct" instead of "Wrong".
Would you be so kind to answer why it works in such manner.
You are using an or operation, so when age is 100 the first part of the OR operation is true which means that the entire OR condition is true because true OR false is true.
You need to use and AND operator
var one = prompt("Enter the number", "4");
var age = parseInt(one);
if (age >= 14 && age <= 90) {
console.log("Correct");
} else {
console.log("Wrong")
}
Any number will return true, because any number is > 14 OR < 90.
If you need the age to be between 14 and 90, do it this way:
if ( age >=14 && age <= 90 )
I got ur Requirement instead of Using OR Operator i.e "||" you should use AND Operator i.e "&&" then u will get the desired result its a logical error

A quick way to test equality of more than 2 values at once?

I was wondering if there was a quick way to test the equality of more than two values in js. Something similar to (= 6 6 6).
In the console, I tried things like...
1 == 1 == 1 == 1
true
2 == 2 == 2 == 2
false
0 == 0 == 0
false
0 == 0 == 0 == 0
true
...which was amusing, but also puzzling.
Is there a quick way of doing this in js?
Thanks.
The reason you got unexpected behavior is because we need to adjust your expectations in js a bit ;) 2 == 2 == 2 == 2 does 3 comparisons, all from left to right. The first comparison is the leftmost 2 == 2, which evaluates to true. After that we get the result of the first comparison being compared to (what is in this case) the 3rd 2. Ie, true === 2, which is false. And finally, we get false === 2, which is also false.
It might help to visualize it as such:
(((2 == 2) == 2) == 2)
I think in general a === b && b === c might be what you're looking for.
EDIT: Ah, and sorry I keep switching out the == for ===. It's just habit. And it's a habit I'd recommend. the === operator doesn't do type casting, so it evaluates the value proper, not a casted version of the value.
It's because true == 1 but true != 2
You can try:
function isEquals() {
var flag = true;
for(var i=1; i<arguments.length; i++) flag = flag && (arguments[i] == arguments[0]);
return flag;
}
isEquals(2,2,2); // true
or:
function isEquals() {
var ar = arguments;
return Array.prototype.every.call(arguments, function(a){return a==ar[0];});
}
Yes you can, but you need to use the "Logical Operators" like the && or || to check more than 1 statement like (x<1 && y>0).
You can use this as a quick easy reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
If you have more than three values, it might be more convenient to create a function for use on an array:
function allEqual(arr) {
return arr.every(function (x, i) {
return i === 0 || x === arr[i - 1];
});
}
allEqual([1, 1, 1])
ES6:
function allEqual(...arr) {
return arr.every((x, i) => i === 0 || x === arr[i - 1]);
}
allEqual(1, 1, 1)
As an addition to #vp_arth's answer you could even add a method to the Array prototype
Array.prototype.isHomogeneous = function(){
return Array.prototype.every.call(this, function(c,i,a){ return c === a[0];})
}
So you could do
[1,2,3].isHomogeneous() = false
[1,1,1].isHomogeneous() = true

Categories