Multiple if statements are executing in succesion? - javascript

I have many if statements the are supposed to trigger on a left or right key press. But when I hit left, it just executes the left key press on all the if statements, even though there are conditons for each statement.
var currentBranch = 1;
if ((currentBranch == 1) && (keyPressed[key.left] == true)){
background.image.src = treeStructure[0][0];
currentBranch = 3;
console.log(currentBranch);
} else if ((currentBranch == 1) && (keyPressed[key.right] == true)) {
background.image.src = treeStructure[0][1];
currentBranch = 2;
console.log(currentBranch);
}
if ((currentBranch == 3) && (keyPressed[key.left] == true)){
background.image.src = treeStructure[1][0];
currentBranch = 4;
console.log(currentBranch);
} else if ((currentBranch == 3) && (keyPressed[key.right] == true)) {
background.image.src = treeStructure[1][1];
currentBranch = 9;
console.log("hello");
console.log(currentBranch);
}
if ((currentBranch == 4) && (keyPressed[key.left] == true)){
background.image.src = treeStructure[2][0];
currentBranch = 6;
console.log(currentBranch);
} else if ((currentBranch == 4) && (keyPressed[key.right] == true)) {
background.image.src = treeStructure[2][1];
currentBranch = 5;
Shouldn't the currentBranch variable stop it after each if statement, for a new key press?

As written, your code is actually 3 separate if... else if... blocks, not one set of chained if blocks. This means that their "truthiness" will be evaluated individually, rather than breaking out after one has evaluated to true.
The first "if..." block evaluates to true, and then inside of that block, you set the variable "currentBranch" to 3, which causes the next if block to evaluate to true, and so on down the line.
You need to change the structure of your code to this:
if (statement) {
//code
}
else if (statement) {
//code
}
else if (statement) {
//code
}
else if (statement) {
//code
}
else if (statement) {
//code
}
else if (statement) {
//code
}
This way, the lower blocks won't be evaluated once a block has evaluated to true.

Related

How to display the number of mistypes in js after the game is over?

The subject will be displayed randomly, and if you write any of (same value, different value, empty value) in the text box, click and press the OK button, you will proceed to the next problem even if the values are not exactly the same. After repeating this process 5 times, I would like to display the number of erroneous inputs.
Look at this if/else if block:
document.addEventListener("keypress", function(e) {
if(e.key === questionList[question].charAt(index) ){
document.forms[0].elements[0].value = "";
index++;
} else if (e.key === 'Shift') {
;
} else if(index == questionList[question].length){
document.forms[0].elements[0].value = "";
index++;
} else if(e.key !== questionList[question].charAt(index)){
typecount++;
} else {
typemiss++;
}
});
The if statement at the beginning checks this:
e.key === questionList[question].charAt(index)
The else if statement before the else checks this:
e.key !== questionList[question].charAt(index)
One or the other will be true. Which means it will never reach the else where you have the typemiss counter incremented.
I have not checked if the following works completely like you wanted but it could help find the error for you:
document.addEventListener("keypress", function(e) {
var isTyping = false;
if(e.key === questionList[question].charAt(index) ){
document.forms[0].elements[0].value = "";
index++;
isTyping = true;
} else if (e.key === 'Shift' || e.key === 'Alt') {
;
} else if(index == questionList[question].length){
document.forms[0].elements[0].value = "";
index++;
} else if(e.key !== questionList[question].charAt(index)){
typemiss++;
isTyping = true;
}
if (isTyping) {
typecount++;
}
});

How to do Event delegation for an Array?(or NodeList)

I'm trying to use the Event delegation/switch statement for the first time in my life, and I'm having trouble with for loop. When it was 'array[i]' it wasn't a problem. But now I'm removing the for loop to use the event delegation and putting it inside of a function, it keeps giving me errors, and I don't know what parameter can replace (and make the code work again) that array[i] in the new function. Any help or explanation will be appreciated.
//original code
const numbers = document.querySelectorAll(".number");
for (let i = 0; i < numbers.length; i++) {
numbers[i].addEventListener("click", function () {
if (display.value.length < 13) {
return;
}
if (display.value == "0" && numbers[i] != dot) {
display.value = numbers[i].innerText;
calculation = display.value;
} else {
if (numbers[i] == dot && display.value.includes(".")) {
return;
} else if (numbers[i] == dot && display.value == "") {
return;
} else {
display.value += numbers[i].innerText;
calculation = display.value;
}
}
buttonEffect(numbers[i], "number-active");
});
}
// New code
const numbers = document.querySelectorAll(".number");
function numberClick(number) {
if (display.value.length > 13) {
return;
}
if (display.value == "0" && this != dot) {
display.value = number.innerText;
calculation = display.value;
} else {
if (numbers == dot && display.value.includes(".")) {
return;
} else if (number == dot && display.value == "") {
return;
} else {
display.value += number.innerText;
calculation = display.value;
}
}
operatorOnOff = false;
buttonEffect(number, "number-active");
}
document.querySelector(".wrapper").addEventListener("click", (e) => {
switch (e.target.dataset.key) {
case "number":
numberClick();
break;
}
});
You pass the element that was the target of the click into numberClick and use it where previously you used numbers[i]. It looks like you're already doing the second part of that, and you even have a parameter declared for it, you just need to pass the element in:
numberClick(e.target);
Note that if your .number elements have child elements, target may be one of those child elements rather than .number. To handle that, you can use the DOM's relatively-new closest method, probably combined with contains to make sure it didn't match something surrounding .wrapper:
document.querySelector(".wrapper").addEventListener("click", (e) => {
const number = e.target.closest(".number");
if (number && this.contains(number) && number.dataset.key) {
numberClick(number);
}
});
There are polyfills you can use if you need to support obsolete browsers, or just do the loop yourself:
document.querySelector(".wrapper").addEventListener("click", (e) => {
let number = e.target;
while (number && !number.matches(".number")) {
if (this === number) {
return; // Reached the wrapper without finding it
}
number = number.parentElement;
}
if (number && number.dataset.key) {
numberClick(number);
}
});

if statements being skipped even when both expressions are true

I have a webpage that populates a table with arrays. It has a doClick function so that when a user clicks on a cell it passes the row and column of the cell to the function. Example cell: onclick="doClick(0,1)"
function doClick(row, col)
{
var top = row -1;
var bottom = row +1;
var left = col -1;
var right = col +1;
var swapped = false;
if ((top != -1) && (cells[top][col].innerHTML = ""))
{
cells[top][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((right != 4) && (cells[row][right].innerHTML = ""))
{
cells[row][right].innerHTML = cells[row][col].innerHTML ;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((bottom != 4) && (cells[bottom][col].innerHTML = ""))
{
cells[bottom][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((left != -1) && (cells[row][left].inn = ""))
{
cells[row][lef].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
. The problem is, even if both if expressions are true, the if statement is being skipped and it's falling through to the else statement. I've desk checked it and run it through the developer tools and checked values. A statement that was true on both expressions was skipped. Any suggestions?
cells[row][right].innerHTML = ""
is wrong. You are missing the double (triple) =.
The correct way should be...
cells[row][right].innerHTML === ""
It looks like maybe there are a few typos or misconceptions in your code.
A quick note about Conditions in an IF statement
A statement like (cells[top][col].innerHTML = "") as a condition will always return true as this is setting cells[top][col].innerHTML as "" or at least instantiating the variable. So, the proper condition to test absolutely true or false would be (cells[top][col].innerHTML === ""). However, you can get away with not even doing that and simply replace (cells[top][col].innerHTML = "") with cells[top][col].innerHTML. You may run into some other issues though is the variable is not instantiated already, either way. I would wrap the latter logic in an IF statement to check if cells[top][col].innerHTML is even instantiated.
To fix this, check out the following modifications I have made to your code.
function doClick(row, col)
{
var top = row -1;
var bottom = row +1;
var left = col -1;
var right = col +1;
var swapped = false;
if(typeof cells[top][col].innerHTML !== 'undefined' $$ cells[top][col].innerHTML !== null)
{
if ((top != -1) && cells[top][col].innerHTML !== '')
{
cells[top][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((right != 4) && cells[row][right].innerHTML !== '')
{
cells[row][right].innerHTML = cells[row][col].innerHTML ;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((bottom != 4) && (cells[bottom][col].innerHTML))
{
cells[bottom][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
}
else if (typeof cells[row][left].inn !== 'undefined' && (left != -1) && cells[row][left].inn !== '')
{
cells[row][lef].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
}
An example working to demonstrate the above code
var testVar1 = '';
var testVar2 = 'Hello';
// var testVar3; <- Left this un-instantiated to test existance
// Testing if a var is empty but exists
if(typeof testVar1 !== 'undefined' && testVar1 !== null){
if(testVar1 !== ''){
alert('testVar1 has a value!');
}{
alert('testVar1 does not have a value!');
}
}
// Testing if a var is empty but exists
if(typeof testVar2 !== 'undefined' && testVar2 !== null){
if(testVar2 !== ''){
if(testVar2 === 'Hello'){
alert('testVar2 has a value! Value: ' + testVar2);
}{
alert('testVar2 has a value but it is not the one we expected.');
}
}{
alert('testVar2 does not have a value!');
}
}
// Test existance
if(typeof testVar3 !== 'undefined' && testVar3 !== null){
alert('testVar3 exists!');
}else{
alert('testVar3 does not exist!');
}

Skip Iteration Google Apps Script

I have a very simple For Loop in Google Apps Script to check some conditions in a Google Sheet. What I want is to add another condition, if it is met, then I want to skip current iteration and move on to next. This is pretty easy in VBA, but I am not sure how to do it on JavaScript.
Current code:
for (var i=1 ; i<=LR ; i++)
{
if (Val4 == "Yes")
{
// Skip current iteration... <-- This is the bit I am not sure how to do
}
elseif (Val1 == "Accepted" && !(Val2 == "") && !(Val3 == ""))
{
// Do something..
}
else
{
// Do something else...
}
}
continue statement can be used to continue to next itteration :
for (var i=1 ; i<=LR ; i++)
{
if (Val4 == "Yes")
{
continue; // Skip current iteration...
}
// Do something else...
}
In your sample case, leaving the if block empty will achieve the same result:
for (var i=1; i <= LR; i++)
{
if (Val4 == "Yes")
{
}
elseif (Val1 == "Accepted" && !(Val2 == "") && !(Val3 == ""))
{
// Do something..
}
else
{
// Do something else...
}
}

Double Condition

It will make selection words starting with "p" and ending with "a". Why it didnt work?
function checkWord(word) {
if (word.charAt(0) = 'p' && word.charAt(word.length - 1) = 'a') {
return true;
} else {
return false;
}
= is used for assigning values, not checking them. Use == for checking the values and === for checking value and types. So, your code should be like:
function checkWord(word) {
if (word.charAt(0) === 'p' && word.charAt(word.length - 1) === 'a') {
return true;
} else {
return false;
}
This should do the trick.
You didn't put 2 equals to if you only put 1 equals you are assigning it and if you put 2 equals you're comparing it the. below code should help
/* Check weather the first letter is equals to p and the last letter is equals to a. */
function checkWord(word) {
let firstPAndLastA = false;
if(word != null){
if (word.charAt(0) == 'p' && word.charAt(word.length - 1) == 'a') {
firstPAndLastA = true;
} else {
firstPAndLastA = false;
}
}
return firstPAndLastA;
}
//Calling Function
console.log(checkWord("ppoa"))

Categories

Resources