Else if statement with 3 or more conditions? - javascript

I have been trying for a long time and cant seem to figure out what i'm doing wrong. The first too conditions seem to work but the third fails.
function spriteAI1() {
if (c2Sprite.position.x >= 30 && c2Sprite.position.x <= 450) {
c2Sprite.translateX( -10 );
} else if (c2Sprite.position.x <= 30 && c2Sprite.position.x >= -450) {
c2Sprite.translateX( 10 );
} else if (c2Sprite.position.z = 30 && c2Sprite.position.x = 30) {
c2Sprite.remove;
c2Sprite.clone;
}
else{}
}
function spriteAI2() {
if (c2Sprite.position.z >= 30 && c2Sprite.position.z <= 350) {
c2Sprite.translateZ( -10 );
} else if (c2Sprite.position.z <= -30 && c2Sprite.position.z >= -350) {
c2Sprite.translateZ( 10 );
} else if (c2Sprite.position.x = 30 && c2Sprite.position.z = 30) {
c2Sprite.remove;
c2Sprite.clone;
}
else{}
}
I'm getting an error on the line
else if (c2Sprite.position.x = 30 && c2Sprite.position.z = 30)
the error says invalid left hand in assignment. But the other function has basically the same line and doesn't generate a error.

I can see two problems in your code.
First, comparison is done using == (double equal signs), not a single one (that's assigning a value). That's probably the source of your problem.
In second place, your last two conditions match a common group of values (they are intersected), in the case when c2Sprite.position.x equals 30, it will enter the second "if". It will match the condition for the third one, but it will not run it.
Make sure you always define well-separated groups of conditions (unless that's the behavior that you want).
Just to make it clear:
if (x >= 30) {
/* this matches 30 and above */
}
else if (x == 30) {
/* this won't execute on x == 30, because it entered the first "if" */
}
You should have done this:
if (x > 30) {
/* this matches numbers strictly greater than 30, i.e. 31, 32, 33... */
}
else if (x == 30) {
/* this will match x == 30 */
}
else {
/* any other value for x */
}

Related

If Else Statement Disaster [duplicate]

This question already has answers here:
How does (A == B == C) comparison work in JavaScript?
(6 answers)
Closed 6 years ago.
today I decided I wanted to make a simple js code that would accept a number (in meters), and decide what the appropriate metric unit to use would be. The code turned out to be a little more complicated than I had expected, but I was able to figure out most of the bugs as I found them (even if it meant rearranging all of my code). However, when it came to my if/else statement I could not figure it out. If I put in a number that is less than 1 nothing happens. If I put in a number more than 9 it logs the same thing every time. The structure itself may need some work, but if someone could help me with the if/else statement I would be very thankful. Here is the code (init is called when the body loads):
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convertDown(x) {
if (0.1 >= x >= 0.99) {
console.log("deci");
}
else if (0.100 >= x >= 0.999) {
console.log("centi");
}
else if (0.1000 >= x) {
console.log("milli");
}
else {
console.log("error");
}
}
function convertUp(x) {
if (1 <= x <= 99) {
console.log("deca");
}
else if (100 <= x <= 999) {
console.log("hecto");
}
else if (1000 <= x) {
console.log("kilo");
}
else {
console.log("error");
}
}
function convertMetricMeters(x) {
if (x < 1) {
convertDown(x);
}
else if (x > 9) {
convertUp(x);
}
else {
console.log("Appropriate Metric Unit");
}
}
}
Use && as AND operator in javascript
Convert these 100 <= x <= 999 to 100 <= x && x <= 999
You could simplify the check a bit and return if a condition is true.
function convertDown(x) {
if (x < 0.01) {
console.log("milli");
return;
}
if (x < 0.1) {
console.log("centi");
return;
}
if (x < 1) {
console.log("deci");
return;
}
console.log("error");
}
Your code has 2 sort of errors. One was simple to fix, that you have to add && between two conditions in if statement.
Now coming to the other part, the less than 1 items. It needed a different logic. Well, your maths seems to be needing bit attention. 0.1 is same as 0.100 and is same as 0.1000
I have updated the code to look for the number of digits after the decimal point and then console.log accordingly.
The updated code will be:
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convertDown(x) {
// checks the number of digits after decimal point
decimals = (x.split('.')[1] || []).length
if (decimals == 1 || decimals == 2) {
console.log("deci");
}
else if (decimals == 3) {
console.log("centi");
}
else if (decimals == 4) {
console.log("milli");
}
else {
console.log("error");
}
}
function convertUp(x) {
if (1 <= x && x <= 99) {
console.log("deca");
}
else if (100 <= x && x <= 999) {
console.log("hecto");
}
else if (1000 <= x) {
console.log("kilo");
}
else {
console.log("error");
}
}
function convertMetricMeters(x) {
if (x < 1) {
convertDown(x);
}
else if (x > 9) {
convertUp(x);
}
else {
console.log("Appropriate Metric Unit");
}
}
}
Working jsfiddle example: https://jsfiddle.net/w7pf3moL/
A simplified version with only 1 method convert(float x):
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convert(x) {
if (x < 0.01) console.log("milli");
else if (x < 0.1) console.log("centi");
else if (x < 1) console.log("deci");
else if (x < 10) console.log("meter");
else if (x < 100) console.log("deca");
else if (x < 1000) console.log("hecto");
else console.log("kilo");
}
function convertMetricMeters(x) {
if (x > 0) {
convert(x);
} else {
console.log("Appropriate Metric Unit");
}
}
}
init();

How NOT to break a function/loop on returning a value (Js)

Hey so I am making a 2D tile game, or really I am just messing around. I have made the map from an array, where 0 represents nothing, and other characters represents a walkable tile.
var map=[["t","t","t","t","t","t","t","t","t","t","t","t","t","t","t","t","t","t","t","t"],
["l","1","b","b","b","b","b","b","b","b","b","b","b","b","b","b","b","b","b","r"],
["l","r","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","r"],
["l","1","t","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","l","r"],
["l","1","1","t","t","t","t","t","t","t","t","t","t","t","t","r","0","0","l","r"],
["l","b","b","b","b","b","b","b","b","1","1","b","b","b","b","b","t","t","b","r"],
["0","0","0","0","0","0","0","0","0","l","r","0","0","0","0","0","0","0","0","0"],
["0","0","0","0","0","0","0","0","0","l","r","0","0","0","0","0","0","0","0","0"],
["0","0","0","0","0","0","0","0","0","l","r","0","0","0","0","0","0","0","0","0"],
["0","0","0","0","0","0","0","0","l","1","1","r","0","0","0","0","0","0","0","0"],
["0","0","0","0","0","0","0","l","1","1","1","1","r","0","0","0","0","0","0","0"],
["t","t","t","t","t","t","t","1","1","1","1","1","1","t","t","t","t","t","t","t"]];
On screen it looks like this
You see my moveable character here as well.
Now I have come this far, and I'd like my character to collide with the empty tiles represented as the value of 0 in my map array.
This is my code for checking collision (brackets are correct in the script):
function collisioncheck(ind){
for(var i in map){
for(var j in map[i]){
if(yass==true){
if(map[i][j]==0){
if(ind==0 && playerPosX==j*32+32 && playerPosY>i*32-32 && playerPosY<i*32+32){
return false;
}else if(ind==1 && playerPosX==j*32-32 && playerPosY>i*32-32 && playerPosY<i*32+32){
return false;
}else if(ind==2 && playerPosY==i*32+32 && playerPosX>j*32-32 && playerPosX<j*32+32){
return false;
}else if(ind==3 && playerPosY==i*32-32 && playerPosX>j*32-32 && playerPosX<j*32+32){
return false;
}else{
return true;
}
}
}else{
return true;
}
}
}
var yass=false;
function exist(){
for(var i in map){
for( var j in map[i]){
if(map[i][j]==0){
yass=true;
break;
}
}
}
So, this works. But only for the first 0 in the map. My problem is that the return statements breaks the for-loop and function. So my character will not collide with any other blank tile but the first one.
I will have to rewrite this, but is there any smart solution to this?
Link to jsfiddle here (Character not visible)
You're on the right track, your loop only runs for one iteration because you always return something after an iteration. However, you should only call return when you know the final result, because - as you said - it will exit the function.
It is correct to call 'return false' right away after a collision is detected, because if the player collides with at least one block, then there is a collision. On the opposite, 'return true' should only be called when you are sure that there are no collisions at all on the entire board, and you need to test every block on the map before you can confirm this.
function collisioncheck(ind) {
for (var i in map) {
for (var j in map[i]) {
if (yass == true) {
if (map[i][j] == 0) {
if (ind == 0 && playerPosX == j * 32 + 32 && playerPosY > i * 32 - 32 && playerPosY < i * 32 + 32) {
return false;
} else if (ind == 1 && playerPosX == j * 32 - 32 && playerPosY > i * 32 - 32 && playerPosY < i * 32 + 32) {
return false;
} else if (ind == 2 && playerPosY == i * 32 + 32 && playerPosX > j * 32 - 32 && playerPosX < j * 32 + 32) {
return false;
} else if (ind == 3 && playerPosY == i * 32 - 32 && playerPosX > j * 32 - 32 && playerPosX < j * 32 + 32) {
return false;
}
// else: do nothing. (i.e. let the loop run for the next block)
}
} else {
return true;
}
}
}
return true;
}
What we do here is go through all the blocks, if we find a collision we return false and exit the function. We only reach the 'return true' statement if we went through all the blocks without finding any collision, which is exactly what you want.
You need to use continue instead of return in the last else of your main if/else block on line 15

If Age is Between 2 Numbers?

I'm trying to direct users to different content based on their age. I'm trying to direct people older than 35 to .if_one, 24-34 to if_two and 18-24 to if_three.. what do I add to check if they are between 18-24 or 25-34?
Here is what I have so far:
$("#age").blur(function() {
$('.a1, .a2').hide();
var age = parseInt($('#age').val());
if (age > 35)
{
$('.if_one').show();
$('#a1').text(age);
alert($('#a1').val());
}
else
{
$('.if_two').show();
$('#a1').text(age);
}
});
You use an if statement with many clauses, and you can use the fact they will be tested in a specific order to your benefit. If you get the second clause, you can assume the first did not trigger, and therefore must not be true.
if (age > 35) {
// triggers if age is over 35
} else if (age > 24) {
// age is not over 35, so triggers if between 24 and 35
} else if (age > 18) {
// age is not over 24, so triggers if between 18 and 24
} else {
// age is not over 18, so triggers if younger than 18
}
You mean like this?
if (age > 35) {
//...
} else if (age >= 24 && age <= 35) {
//...
} else if (age >= 18 && age <= 23) {
//...
} else {
//age is 17 or less, don't know if you want to do something here...
}

javascript if value is number to number

Is there any way to check if value is in a number range? Like my example:
if (battery.level == 70 to 100) {
$('#battery').css('background-image', 'url("battery_full.png")');
}
What's the syntax for that? Thanks for help.
if (battery.level >= 70 && battery.level <= 100) {
something like this
if ( value >= 70 && value <= 100)
{
}
You could do this :
function inRange(n, from, to) {
return n >= from && n <= to;
}
if (inRange(battery.levelPercent, 70, 100))
YOU CAN CHECK NUMBER LIKE
if ( battery.level >= 70 && battery.level <= 100)
{
}
NOT A STRING LIKE ('70%' to '100%')
70% is actually not a number. However, you could get rid of the invalidating % by naming your variable battery.levelPercent instead and adding the percent sign whenever it needs to be output.
Then, you could check the number like this:
if (typeof battery.levelPercent === "number") {
if (battery.levelPercent >= 70 && battery.levelPercent <= 100) {
$('#battery').css('background-image', 'url("battery_full.png")');
} // else, not in range
} // else, not a number
You better remove % from battery.level to compare it with number.
Live Demo
level = battery.level.replace('%', '');
if (level >= 70 && level <= 100) {
$('#battery').css('background-image', 'url("battery_full.png")');
}
You can also use parseFloat or parseInt
level = parseFloat(battery.level);
if (level >= 70 && level <= 100) {
$('#battery').css('background-image', 'url("battery_full.png")');
}

Updating the random number within a variable?

How can a variable with a random number be updated. I'm using three.js. Here is my code. It works the first time it's called generating a sprite to a random location but then it just keeps going back to the same location. I thought that by calling the variables before they were used I would be updating them but it's not working.
var locX = Math.floor((Math.random()*450)+1);
locX *= Math.floor(Math.random()*2) == 1 ? 1 : -1;
var locY = Math.floor((Math.random()*250)+1);
locY *= Math.floor(Math.random()*2) == 1 ? 1 : -1;
var locZ = Math.floor((Math.random()*350)+1);
locZ *= Math.floor(Math.random()*2) == 1 ? 1 : -1;
function spriteAI1() {
//console.log(c2Sprite.position.x);
//console.log(ranLocX);
//console.log(ranTen);
if (c2Sprite.position.x > 30 && c2Sprite.position.x <= 450) {
c2Sprite.translateX( -10 );
} else if (c2Sprite.position.x < -31 && c2Sprite.position.x >= -450) {
c2Sprite.translateX( 10 );
} else if (c2Sprite.position.z < 31 && c2Sprite.position.x < 31 && c2Sprite.position.z > -29 && c2Sprite.position.x > -29) {
locX;
locY;
locZ;
//c2Sprite.delete;
//scene.remove(c2Sprite);
//console.log("AI1");
c2Sprite.position.set( locX, locY, locZ );
//scene.add( c2Sprite );
//c2Sprite.clone;
}
}
If you want different values each call, declare the vars inside the function, not outside of it. As you currently have it, the vars are set once, and the function, however many times it's called, will reference those once-set values.

Categories

Resources