I have a condition like this, I want the first if conditional to have no reaction if you meet this condition again the second time give him a reaction, more or less like the example in the code below.
var x = -1;
if( x < 0){
console.log("is okay")
}if( x < 0 AGAIN ){
console.log("is not okay")
}
CodePudding user response:
add a new variable can solve it:
var x = -1;
var isFirstTime = true;
if( x < 0 && isFirstTime == true){
console.log("is okay");
isFirstTime = false;
}if( x < 0 && isFirstTime == false){
console.log("is not okay");
}
CodePudding user response:
Use a flag variable and initialize it with true
, when it will meet the first negative value (x < 0) print ok
and set the flag to false
. Next time when it got a negative value and the flag is false
print not ok
.
var x = -1;
var firstTime = true;
if( x < 0){
if (firstTime){
console.log("is okay");
firstTime = false;
}
else {
console.log("is not okay")
}
}
Here is a test example:
var firstTime = true;
test_list = [1,-1,2,5,-1,6]
for (let i in test_list){
x=test_list[i]
console.log(x)
if( x < 0){
if (firstTime){
console.log("is okay");
firstTime = false;
}
else {
console.log("is not okay")
}
}
}
Output:
1
-1
"is okay"
2
5
-1
"is not okay"
6