Javascript if statement inside of another if statement [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to put an if statement inside of another if statement, and I think I did something very easy to fix, but I can't figure out what or where it is. I am stuck with this and any suggestions would be helpful. Thanks!
var player = 0;
var xvalue = 0;
var ovalue = 0;
function tic(a)
{
if(player === 0)
{
document.getElementById(a).value = 'X';
document.getElementById(a).disabled = 'true';
player = 1;
if(a === 'aa')
{
var i = 1
for(i = 1; i <= 1; i++; )
{
xvalue++;
}
}
else if(a === 'ab')
{
var i = 1
for(i = 1; i <= 2; i++; )
{
xvalue++;
}
else if(a === 'ac')
{
var i = 1
for(i = 1; i <= 4; i++; )
{
xvalue++;
}
else if(a === 'ba')
{
var i = 1
for(i = 1; i <= 8; i++; )
{
xvalue++;
}
else if(a === 'bb')
{
var i = 1
for(i = 1; i <= 16; i++; )
{
xvalue++;
}
else if(a === 'bc')
{
var i = 1
for(i = 1; i <= 32; i++; )
{
xvalue++;
}
else if(a === 'ca')
{
var i = 1
for(i = 1; i <= 64; i++; )
{
xvalue++;
}
else if(a === 'cb')
{
var i = 1
for(i = 1; i <= 128; i++; )
{
xvalue++;
}
else if(a === 'cc')
{
var i = 1
for(i = 1; i <= 256; i++; )
{
xvalue++;
}
if(xvalue === 448)
{
alert("player 1 wins!");
}
else if(xvalue === 7)
{
alert("player 1 wins!");
}
else if(xvalue === 56)
{
alert("player 1 wins!");
}
else if(xvalue === 273)
{
alert("player 1 wins!");
}
else if(xvalue === 84)
{
alert("player 1 wins!");
}
else if(xvalue === 73)
{
alert("player 1 wins!");
}
else if(xvalue === 146)
{
alert("player 1 wins!");
}
else if(xvalue === 292)
{
alert("player 1 wins!");
}
}
else
{
document.getElementById(a).value = 'O';
document.getElementById(a).disabled = 'true';
player = 0;
}
}

Your code is riddled with syntax errors:
else if(a === 'ab'){
var i = 1
for(i = 1; i <= 2; i++; ){
xvalue++;
}
You're opening the else if block, and inside, you open a for block, but only close one. It should've been:
else if(a === 'ab'){
var i = 1
for(i = 1; i <= 2; i++; ){
xvalue++;
}//<-- close for loops
}// then close else if block
To nest if's is pretty easy, and you seem to be doing it right, but perhaps you were asking if it was possible to combine the outer & inner ifs. In that case: yes:
if (player === 0 && a === 'aaa')
Works perfectly fine, too.
But to be honest you really need to practice a bit more: JS global variables should be avoided: functions should be passed parameters.

Related

Create a function toGradePoints() that takes an array of letter grades as input and returns a corresponding array of grade points [duplicate]

This question already has answers here:
Javascript if statements not working [duplicate]
(3 answers)
Closed 3 years ago.
function toGradePoints(letter) {
//var score = '';
var grade = [];
for (var i = 0; i < letter.length; i++)
{
//result = '';
if (letter[i] = "A") {
grade[i] = 4.0;
} else if (letter[i] = "A-") {
grade[i] = 3.7;
} else if (letter[i] = "B+") {
grade[i] = 3.3;
} else if (letter[i] = "B") {
grade[i] = 3.0;
} else if (letter[i] = "B-") {
grade[i] = 2.7 ;
} else if (letter[i] = "C+") {
grade[i] = 2.4;
} else if (score[i] = "C") {
grade[i] = 2.0;
} else if (score[i] = "C-") {
grade[i] = 1.7;
} else {
grade[i] = 0;
}
// result.push(score);
}
return grade;
}
var y=[]
y=["B","B+","C-","D"];
var m=toGradePoints(y);
console.log(m)
Here is the link, q1.2
It only displays 4 all the time, I don't know which part went wrong.
You are assigning value with = instead of comparing with an operator == when checking the alphabetic grade.
letter[i] = "A"
Should be:
letter[i] == "A"
Also you have a type you refer in a couple of if conditionals to a wrong score which should be changed to letter.
Full code fixed:
function toGradePoints(letter) {
//var score = '';
var grade = [];
for (var i = 0; i < letter.length; i++)
{
//result = '';
if (letter[i] == "A") {
grade[i] = 4.0;
} else if (letter[i] == "A-") {
grade[i] = 3.7;
} else if (letter[i] == "B+") {
grade[i] = 3.3;
} else if (letter[i] == "B") {
grade[i] = 3.0;
} else if (letter[i] == "B-") {
grade[i] = 2.7 ;
} else if (letter[i] == "C+") {
grade[i] = 2.4;
} else if (letter[i] == "C") {
grade[i] = 2.0;
} else if (letter[i] == "C-") {
grade[i] = 1.7;
} else {
grade[i] = 0;
}
// result.push(score);
}
return grade;
}
var y=[]
y=["B","B+","C-","D"];
var m=toGradePoints(y);
console.log(m)

JS Alert when items collected?

I have created a maze game where the user must collect all the coins in the maze, however I am trying to make an alert appear once the user has collected all the coins, not in any particular order just in general. The alert is being very troublesome at the moment and not working correctly and I'm not sure where I am going wrong based off my research into the matter. I am new to JavaScript so apologies for any clear mistakes.
EDIT I GOT TOLD TO REPHRASE MY QUESTION MORE DIRECTLY - SO THIS ISN'T A DUPLICATE QUESTION. I ALSO HAVE A MAP DECLARDED BUT CANNOT UPLOAD AS IT'S TOO MUCH CODE.
Also, when I say not working correctly, it will appear at random counts as supposed to when the last reward has been collected.
var el = document.getElementById('game');
function drawWorld(){
el.innerHTML = '';
for(var y = 0; y < map.length ; y = y + 1) {
for(var x = 0; x < map[y].length ; x = x + 1) {
if (map[y][x] === 1) {
el.innerHTML += "<div class='borders'></div>";
} else if (map[y][x] === 2) {
el.innerHTML += "<div class='reward'></div>";
} else if (map[y][x] === 3) {
el.innerHTML += "<div class='ground'></div>";
} else if (map[y][x] === 5) {
el.innerHTML += "<div class='character'></div>";
} else if (map[y][x] === 4) {
el.innerHTML += "<div class='ship'></div>";
}
}
el.innerHTML += "<br>";
}
winGame();
}
function restartGame(){
window.location.reload();
}
function winGame(){
if (!map[5].includes(2) && !map[2].includes(2) &&
!map[3].includes(2) && !map[2].includes(2) && !map[4].includes(2)
&& !map[2].includes(2))
alert("Well done!");
}
drawWorld();
document.onkeydown = function(event){
if (event.keyCode === 37){
if ( map[character.y][character.x-1] !== 1){
map[character.y][character.x] = 3;
character.x = character.x - 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 38){
if ( map[character.y-1][character.x] !== 1){
map[character.y][character.x] = 3;
character.y = character.y - 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 39){
if ( map[character.y][character.x+1] !== 1){
map[character.y][character.x] = 3;
character.x = character.x + 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 40){
if ( map[character.y+1][character.x] !== 1){
map[character.y][character.x] = 3;
character.y = character.y + 1;
map[character.y][character.x] = 5;
drawWorld();
}
}
console.log(map)
}

Variable only works locally

I wrote some functions involving prime factorization and I noticed that when I identified my test paragraph (for testing the results of functions and such) as document.getElementById("text"), it worked fine. However, when I declared a global variable text as var text = document.getElementById("text"), and then substituted in text for the longer version, it no longer worked. I did, however, notice that it worked when I locally declared text. Why is this and how can I fix it? My JSFiddle is here: https://jsfiddle.net/MCBlastoise/3ehcz214/
And this is my code:
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
}
else if (num === 2) {
return true;
}
else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
}
else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
}
else if (dig === 2) {
return undefined;
}
else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
}
else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
}
else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
}
else if (isPrime(int) === true) {
return false;
}
else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
}
else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
//text.innerHTML = isPrime(6);
<div onclick="listPrimes()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
The text is global, you just need to make sure the whole script file is included in the html. Here's an example of what I mean
Here in code snippets stackoverflow does this for us already.
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
} else if (num === 2) {
return true;
} else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
} else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
} else if (dig === 2) {
return undefined;
} else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
} else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
} else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
} else if (isPrime(int) === true) {
return false;
} else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
} else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
function test() {
console.log("inside test1")
console.log(text);
text.innerHTML = "testtt"
}
function test2() {
console.log("inside test2")
console.log(text);
text.innerHTML = "testtt2"
}
text.innerHTML = isPrime(6);
<div onclick="test()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
<div onclick="test2()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
In the head the script runs/loads first and because you don't have the var's in a function they are never re-used they remain with the original value which is null since the document didn't exist at that time, then when the page loads all it has is access to the functions a call to the global var is null. This is why the code previously only worked when text = document.getElementById('text') was in a function.

NaN error equation

In this javascript code I try to solve a quadratic equation, I've been working on it for an hour and this should tell me the value of a, b and c where y is a(x^2). I'm a relative javascript beginner and would love some help. Why are the values of a, b and c not numbers? The variable names are in italian, in english and in something else(Not even I know what), but I commented what they are. That's one of my bad traits as a student that usually works alone, sorry if it's not easy to understand.
<script type="text/javascript">
var equa=prompt("Scrivi l'equazione senza spazi usando x come incognita e y come x^2");
var a = 0.0; b = 0.0; c = 0.0;//ax2+bx+c
var prima = true; //before or after equal?
var ope = 1;//1add 2sub 3mul 4div
var lasto = 0.0;//last number, used for div and mul
var lastos = 3; //1a2b3c
var errore=0;//is something messed up?
for(var i = 0; i < equa.length;i=i){
if(equa.charAt(i)=='='){
prima = false;
i++;
}else if(equa.charAt(i)=='+'){
ope=1;
i++;
}else if(equa.charAt(i)=='-'){
ope=2;
i++;
}else if(equa.charAt(i)=='*'){
ope=3;
i++;
}else if(equa.charAt(i)=='/'){
ope=4;
i++;
}else{
var nume = "";//Current number in string form
while(i<equa.length && equa.charAt(i)>'0' && equa.charAt(i)<'9'){
nume+=equa.charAt(i);
i++;
}
var lasnum = 0.0;//current number in float form
var lasval = 3; //1a2b3c
if(equa.charAt(i) == 'x'){
lasnum=parseFloat(nume);
lasval = 2;
}else if(equa.charAt(i) == 'y'){
lasnum=parseFloat(nume);
lasval = 1;
}else{
lasnum = parseFloat(nume);
lasval=3;
}
i++;
if( (ope == 1 || ope == 2) && !(equa.charAt(i) =='*' || equa.charAt(i) == '/')){
if(lasval == 1){
if(prima) a+=lasnum;
else a-=lasnum;
}
else if(lasval == 2){
if(prima) b+=lasnum;
else b-=lasnum;
}
else {
if(prima) c+=lasnum;
else c-=lasnum;
}
}else if( (ope==1 || ope == 2) && (equa.charAt(i) =='*' || equa.charAt(i) == '/')){
//zitto e fermo
lasto=lasnum;
lastos=lasval;
}else if( (ope==3||ope == 4)){
if(ope==3){
if(lastos==3){
lasnum*=lasto;
}
if(lastos == 2){
if(lastval==3){
lasnum*=lasto;
lastval=2;
}
if(lastval==2){
lasnum*=lasto;
lastval=1;
}
if(lastval==1){
errore=1;
}
}
if(lastos == 1){
if(lastval == 3){
lasnum*=lasto;
lastval=1;
}else{
errore=1;
}
}
}
if(ope == 4){
if(lastos == 1){
if(lastval==3){
lasnum/=lasto;
lastval=1;
}
if(lastval==2){
lasnum/=lasto;
lastval=2;
}
if(lastval==1){
lasnum/=lasto;
lastval=3;
}
}
if(lastos == 2){
if(lastval==1){
errore=1;
}
if(lastval==2){
lasnum/=lasto;
lastval=3;
}
if(lastval==3){
lasnum/=lasto;
lastval=2;
}
}
if(lastos == 3){
if(lastval==3){
lasnum/=lasto;
}else{
errore=1;
}
}
}
if(equa.charAt(i) =='*' || equa.charAt(i) == '/'){
lasto=lasnum;
lasto=lasval;
}else{
if(lasval == 1){
if(prima) a+=lasnum;
else a-=lasnum;
}
else if(lasval == 2){
if(prima) b+=lasnum;
else b-=lasnum;
}
else {
if(prima) c+=lasnum;
else c-=lasnum;
}
lasto=0;
lastos=3;
}
}
}
}
if(errore==0){
alert("a ="+a+" b="+b+" c="+c);
}else{
alert("AOOOOOOo");
}
</script>
Since the expected input should be in the format "15y+3x+5=20" for example, then this is a simple regular expression:
var equa = prompt("Scrivi l'equazione senza spazi usando x come incognita e y come x^2");
var regex = /^([0-9.]+)y\+([0-9.]+)x\+([0-9.]+)=([0-9.]+)$/;
var matches = regex.exec(equa);
if (matches) {
var a = parseFloat(matches[1]);
var b = parseFloat(matches[2]);
var c = parseFloat(matches[3]) - parseFloat(matches[4]);
var discriminant = b*b - 4*a*c;
if (discriminant < 0) {
alert('No real solutions');
}
else {
var root = Math.sqrt(discriminant);
alert('Root: ' + ((-b + root)/(2*a)) + ', ' + ((-b - root)/(2*a)));
}
}
else {
alert("AOOOOOOo");
}

How to move an element in javascript automatically with while loop?

I am making a Snake game so I'm trying to move my snake. It is moving with keys but it should move automatically on the screen. I tried doing that with while loops like in the code below but because of break; I have to press a key every time I want it to move. How can I make it move automatically? I tried removing break; an using an if statement but I didn't succeed.
Any other solutions or something else?
I'm new to programming so any advices would be helpful.
var main = function() {
var i = 0;
var j = 0;
$(document).keyup(function(event) {
var e = event.which;
while(i == 1) {
$('.snake').animate({left: '+=10px'}, 10);
break;
}
while(i == 2) {
$('.snake').animate({left: '-=10px'}, 10);
break;
}
while(i == 3) {
$('.snake').animate({top: '-=10px'}, 10);
break;
}
while(i == 4) {
$('.snake').animate({top: '+=10px'}, 10);
break;
}
//Which key is preesed
//D
if(e == 68) {
i = 1;
}
//A
else if(e == 65) {
i = 2;
}
//W
else if(e == 87) {
i = 3;
}
//S
else if(e == 83) {
i = 4;
}
//Any other key
else {
i = 0;
}
});
};
$(document).ready(main);
I think you just have to organize a little bit your code.
First. You must put your code inside a function. You really don't need a while. You can use a simple if.
function move(i) {
if(i == 1) {
$('.snake').animate({left: '+=10px'}, 10);
break;
}
if(i == 2) {
$('.snake').animate({left: '-=10px'}, 10);
break;
}
if(i == 3) {
$('.snake').animate({top: '-=10px'}, 10);
break;
}
if(i == 4) {
$('.snake').animate({top: '+=10px'}, 10);
break;
}
}
Now you have to change the event, using keydown instead of keyup
function main() {
var interval;
$(document).keydown(function(event) {
if(interval) clearInterval(interval); // Clear the previous interval
var e = event.which;
var i;
//Which key is pressed
//D
if(e == 68) {
i = 1;
}
//A
else if(e == 65) {
i = 2;
}
//W
else if(e == 87) {
i = 3;
}
//S
else if(e == 83) {
i = 4;
}
//Any other key
else {
i = 0;
}
interval = setInterval(function() {
move(i)
},1000); // repeat every 1 second
});
}
$(document).ready(main);

Categories

Resources