simple comparison script doesnt seem to work - javascript

I keep getting a syntax error caused by the final else statement at the end of the script. This seems to stop anymore JS running on the page, but I can't figure out why it's causing an error. More than likely, it's a really simple syntax thing that I just can't see, because I've been looking at it too long. If anyone could help that would be great. I've declared the variables in the code, but in the actual program these are based on other conditions and will be integers.
var nbdJDay = 70;
var mmWindow = 1;
var dayCompare = nbdJDay;
if (dayCompare < 85 && dayCompare > 14) {
mmWindow = 2;
} else if (dayCompare < 15 && dayCompare > -15) {
mmWindow = 3;
} else {
mmWindow = 0;
}

Related

Javascript - if-statement with multiple numeric conditions doesn't work

I'm trying to make a simple program in javascript+html. If exp exceeds within a certain range/exceeds a certain number, the level displayed goes up by 1. I've tried to make it show onload, but the level doesn't change no matter what happens to the exp staying at the highest one I've written code for so far.
Javascript:
var exp6 = localStorage.exp6;
var pexp6 = parseInt(exp6);
function char6() {
res.innerHTML = res6;
var lsps = pexp6;
localStorage.setItem("lsp", lsps);
return PrUpdate();
}
var lsp = localStorage.lps;
function PrUpdate() {
if (lsp <= 999) {
lvl.innerHTML = 1;
}
else if (lsp >= 1000 && lsp <= 1999) {
lvl.innerHTML = 2;
}
else if (lsp >= 2000 && lsp <= 2999) {
lvl.innerHTML = 3;
}
else if (lsp >= 3000 && lsp <= 3999) {
lvl.innerHTML = 4;
}
else if (lsp >= 4000 && lsp <= 4999) {
lvl.innerHTML = 5;
}
}
I've also included the setChar() function in the window.onload of the page. I've tried including the function itself in it as well, but whether I add it at the end of the setChar() or in the window.onload the problem stays the same. All other functions work fine, it's just this part that doesn't. I'm also trying to make it generic to fit other 'accounts' I'm trying to make to save myself time. But I just can't make it work.
Edit:
I've figured out why it didn't work, and it was cause I had my localStorage.lsp in the wrong place.
I'm trying to figure out now how to make it so I don't have to refresh the page to get it to appear.
[ Solved my issue :), if unclear by my edit above]
The way you are trying to access values from localstorage is incorrect. This is not valid: localstorage.exp6.
Instead try this: localstorage.getItem('exp6')
See the documentation of Web Storage API for more information

Refactoring JavaScript function results

I'm working on a project using Leaflet's Mapping API. Right now, I'm cleaning up my code and there's one section I feel could be made better.
I have it set when the location is found, the location is checked both in accuracy and in bounds:
function checkLocation(position)
{
if(position.accuracy > 100)
{
return 4;
}
else if((position.latlng.lat <= **bound** || position.latlng.lat >= **bound**) || (position.latlng.lng >= **bound** || position.latlng.lng <= **bound**))
{
return 5;
}
return 0;
}
Basically, if the accuracy is too low, I throw an error with error code 4. If the coordinates are outside of where I want them to be, I throw an error with error code 5 (These are to correspond to Leaflet's builtin error codes 1-3 so I can switch on them later). I return 0 just to say there wasn't an error.
This function is called by the locationFound event, which has the following code:
var temp = checkLocation(position);
if(temp != 0)
{
// Handle error code
return;
}
This also works, but I'm not fond of how this looks. What I want is for this bit to only take like two to three lines, preferably without an if statement. I originally had the code for checkLocation in this section, but I thought having it on its own would make for cleaner and more reader-friendly code.
My question is is there any way to improve this bit? I looked into lambda expressions but didn't think it fit and I tried using a Promise, but at that point, I was losing lines trying to cut down on lines. I don't want to code golf the code, but I'm still pretty new to JavaScript and I don't know if there's any way to simplify this while still looking professional. I'm also up for changing the checkLocation function if it means improving the code.
If you refactor to this:
function invalidAccuracy(position) {
return position.accuracy > 100;
}
function outOfBounds(position) {
return (position.latlng.lat <= **bound** || position.latlng.lat >= **bound**) || (position.latlng.lng >= **bound** || position.latlng.lng <= **bound**);
}
You can handle it like this:
function checkLocation(position) {
if(invalidAccuracy(position))
return 4;
if(outOfBounds(position))
return 5;
return 0;
}
You can (if you want) put it in 1 line then:
return invalidAccuracy(position) ? 4:
outOfBounds(position) ? 5 :
0;

Collision detection is not returning inside limits

Full code here
I am trying to setup the functions to detect collisions and for now just log to the console. This is the section for checkCollision function;
Player.prototype.update = function(dt) {
checkCollision(this.leftLimit, this.rightLimit);
this.leftLimit = this.x - 40.5;
this.rightLimit = this.x + 40.5;
}
function checkCollision(playerl,playerr) {
for (var i = 0; i < 5; i++) {
var thisEnemy = allEnemies[i];
if (thisEnemy.leftlimit > playerl && thisEnemy.rightLimit < playerr) {console.log("1")}
else {console.log('else')}
}
}
Question
The character is never registering as colliding with the enemy, why is this not working?
Testing/Debugging
I know this function is working as consoles logging else, I've also put logging in other locations and when in the Enemy.prototype.update function, console was showing values like 202.000000093, since the for..else function is using < or >, not absolute values, that should be fine, but still nothing is matching inside the player left and right limits. I also tried changing the Enemy limits to be smaller, +/- 40.5, incase the enemy was too wide to fit inside the player limits.
player.leftLimit and player.rightLimit are undefined when checkCollision method is first running
I added a better if statement to check if there's a collision;
if (
thisEnemy.leftLimit < player.rightLimit &&
thisEnemy.rightLimit > player.leftLimit &&
thisEnemy.upperLimit > player.lowerLimit &&
thisEnemy.lowerLimit < player.upperLimit) {
console.log("collision");
}

JavaScript - conditional throwing an uncaught syntax error

I am currently working on a challenge to convert any amount of arbitrary numbers entered into the function below as a currency (expressed by a string where every three characters are separated by a comma). All was okay until I realized that if the length of the number entered was 4, then the comma would need to be placed as 1,234 rather than 123,4.
It seems the function has spiralled out of control a little when I wrapped the initial if statement around my for loop. (1) I keep getting thrown an 'Uncaught SyntaxError: Unexpected token else' in the console. (2) I thought it may be due trying to place an if/else around the for/if/else. Any light shed on my error would be much appreciated. Charlie
function toCurrency(price){
var newStrng = price.toString().split("");
var stringCh = [];
if(newStrng.length===4){
console.log("gotcha");
stringCh = newStrng.splice(1,0,",");
return stringCh;
} else {
for(var i = 0; i < newStrng.length; i++) {
if(i %3 === 0 && i !== 0){
stringCh.push(",");
stringCh.push(newStrng[i]);
}
} else {
stringCh.push(newStrng[i]);
}
}
var finallyDone = stringCh.join("");
return finallyDone;
}//EO function
The if statement in the following block
for(var i = 0; i < newStrng.length; i++) {
if(i %3 === 0 && i !== 0){
stringCh.push(",");
stringCh.push(newStrng[i]);
}
} else {
stringCh.push(newStrng[i]);
}
}
has an extra }, right before the else. Take it out and you should no long receive the syntax error.
You can make it easier to spot mistakes like this in the future by ensuring your code is properly indented so you can see which brackets are associated with which blocks. Though I appreciate it could be reasonably indented in the source code and may not have copied across to SO perfectly.
There is a } in the wrong place inside the for loop, that need to be moved after the else block. As it is, the if statement is located in the for loop, but the else block is located outside of the loop, which is not valid syntax.
function toCurrency(price){
var newStrng = price.toString().split("");
var stringCh = [];
if(newStrng.length===4){
console.log("gotcha");
stringCh = newStrng.splice(1,0,",");
return stringCh;
} else {
for(var i = 0; i < newStrng.length; i++) {
if(i %3 === 0 && i !== 0){
stringCh.push(",");
stringCh.push(newStrng[i]);
} else {
stringCh.push(newStrng[i]);
}
}
}
var finallyDone = stringCh.join("");
return finallyDone;
}//EO function
remove } after,
stringCh.push(newStrng[i]);

TypeError: Cannot find function 1.0

I have a script and I'm almost done but I get this error and frankly I have no idea what is wrong here. I'm rather new to Javascript so I suspect I did something wrong in the syntax somewhere. Here is an extract from the script containing the offending line :
var gc = 0;
var seg;
var segCount = 0;
var groupCount = 0;
var groupLevel = 0;
var segments = new Array();
var sk = "";
for(gc = 0; gc <= groupLevel; gc++)
{
if(gc >= groupDelimiters.length) break;
if(seg.name() == groupDelimiters[gc])
{
//ok we start another group
grKeys.startNewGroup(groupLevel, groupCriterionExtractors[groupLevel](segCount), groupCount);
groupLevel = gc + 1; //This line is flagged with the error in the title
groupCount++;
}
}
ideas, pointers, any help would be appreciated.
edit - I got screwed by the $%*& markup syntax from outer space. Here is the code as it should have appeared.
It's hard to tell without more info but I would guess from the error message that the following code:
groupCriterionExtractors[groupLevel]
is yielding the value 1.0 which you are then trying to call with:
(segCount)
So it's like saying:
grKeys.startNewGroup(groupLevel, 1.0(segCount), groupCount);
There are several problems with the above code such as the for loop, post what you're trying to do and some test data and I can help more
there’s a { missing in your code and the for() syntax is wrong.
for ([initialExpression]; [condition]; [incrementExpression])
ah, yes, your for() loop won’t execute anything as it is now.
This:
for(gc = 0; gc = groupDelimiters.length) break;
if (seg.name() == groupDelimiters[gc])
...
Should probably be
for (gc = 0; gc < groupDelimiters.length; gc++) {
if (seg.name() == groupDelimiters[gc])
...

Categories