I have a function that has to act different if pan.cost > 0.
So let's say curPos = 3 and pan.cost = -1
Now when I do this, no matter what, if(curPos + 1 === 5 || 30) is always used even if curPos + 1 is 2,3,4,6 etc (as long pan.cost < 0)
Now I have put console.log(curPos + 1) inside the else if-statement and it also says their that it does not meet the requirements.
function action(curPos)
{
var pan = panel[curPos];
if(pan.cost > 0)
{
}
else if(curPos + 1 === 5 || 39)
{
console.log(curPos + 1);
}
else if(curPos + 1 === 3)
{
console.log("should be here");
}
}
Try this:
function action(curPos)
{
var pan = panel[curPos];
var newCurPos = (curPost + 1);
if(pan.cost > 0)
{
}
else if(newCurPos === 5 || newCurPos === 39)
{
console.log(newCurPos);
}
else if(newCurPos === 3)
{
console.log("should be here");
}
}
The line
curPos + 1 === 5 || 39
always evaluates to truthy, because it is read:
(curPos + 1 === 5) || 39
and 39 is a truthy value.
if(curPos + 1 === 5 || 39) will always evaluate to true. Look at the part after your or pipes. if(39) will always be true.
|| 39 will always return true and pan.cost doesn't exist.
Related
My code here
if (parent4 && parent5 && parent6 && (_state[tree][parent4]) + (_state[tree][parent5]) + (_state[tree][parent6]) !== 8) {
return false;
} else {
return true;
}
It works, and has some of the elements I want, namely that if the sum of the three _states !== 8, it returns false.
I'll try to explain the logic I'm trying to achieve as simply as I can:
if par4 + par5 + par6 !>= 8
return false
if par4 + par5 !>= 8
return false
if par4 OR par5 OR par6 !>= 8
return false
else
return true
I abbreviated the code for simplicity and ease of understanding.
Swapping around return false and return true and changing it to >= doesn't work, because for all elements, even ones I don't mention here, it needs to go to return true by default.
How about this?
if (parent4 && parent5 && parent6) {
if ((_state[tree][parent4] + _state[tree][parent4] + _state[tree][parent4]) !== 8) {
return false;
} else {
return true;
}
}
Or in a one-liner:
if (parent4 && parent5 && parent6 && (_state[tree][parent4] + _state[tree][parent4] + _state[tree][parent4]) !== 8) {
return false;
} else {
return true;
}
I was working on an HTML music creator. I am getting an error every time I run a JavaScript function to add an onClick attribute to every td element starting from the eighth element of the td tags. I get the error:
"Uncaught TypeError: cannot set property 'onClick' of undefined."
Here is my JavaScript:
function addOnclick() {
var num = 1;
var note = 0;
i = 8;
while (i < (17 * 12) + 8 + 1) {
document.getElementsByTagName("td")[i].onClick = "switchNote(" + num + ", " + note + ")";
if (i == 25 || i == 42 || i == 59 || i == 76 || i == 81 || i == 98 || i == 115 || i == 132 || i == 149 || i == 166 || i == 183 || i == 200 || i == 217) {
note = note + 1;
num = 1;
}
i = i + 1;
num = num + 1;
console.log("working");
}
}
If you have any idea, please help!
Thanks,
Tendel T.
Two things,
You need to check if the element exists (difficult to tell without your markup).
try something like
var element = document.getElementsByTagName("td")[i];
element && element.onclick = function(){
switchNote( num, note )
};
Value of an onclick handler cannot be a string, it has to be a function.
Instead of assigning value to OnClick you should use setAttribute and check whether element has been defined or not as shown below:
function addOnclick() {
function addOnclick() {
var num = 1;
var note = 0;
i = 8;
while (i < (17 * 12) + 8 + 1) {
var elem = document.getElementsByTagName("td")[i];
if (elem)
{
elem.setAttribute('onclick', "switchNote(" + num + ", " + note + ")")
}
if (i == 25 || i == 42 || i == 59 || i == 76 || i == 81 || i == 98 || i == 115 || i == 132 || i == 149 || i == 166 || i == 183 || i == 200 || i == 217) {
note = note + 1;
num = 1;
}
i = i + 1;
num = num + 1;
console.log("working");
}
}
}
I am trying to create the Bagel game and keep getting missing ) after argument list when I try to create the guess variable right after the for statement. Can someone tell me how to fix this?
alert('Lets play the bagel game! If you can guess my three digit number (with each digit being unique) within 20 turns, then you win! I will only provide you with three hints. Pico, which means one digit is correct, but in the wrong position. Fermi, which means one digit is correct and in the right position. Bagels, which means no digits are correct');
//computer generates number
function numberRange(){
var number = Math.round(Math.random()*1000);
var num =number.toString();
if (number <= 100 || number == 1000){
numberRange();
}
else if (num[0] == num[1] || num[0] == num[2] || num[1]==num[2]){
numberRange();
}
else if (number == undefined || num == undefined){
numberRange();
}else{
var numSave = JSON.stringify(num);
sessionStorage.setItem('number',numSave);
}}
numberRange();
var numGet = sessionStorage.getItem('number');
var numUse = JSON.parse(numGet);
//game start
for (i=1;i<21;i++){
var validNumber = /\d{3}/;
var guess = prompt('Turn ' + i ': Guess a number!');
while (validNumber.test(guess) == false) {
alert('Put in a three digit number!');
var guess = prompt('Turn ' + i ': Guess a number!');
}
if (validNumber.test(guess)){
var guessNum = guess.toString();
if (guessNum[0] == numUse[0] && guessNum[1] && numUse[1] && guessNum[2] == numUse[2]){
alert('Congratulations! You win!');
break
}
else if ((guessNum[0] == numUse[0] || guessNum[1] == numUse[1] || guessNum[2] == numUse[2]) && (guessNum[0] == numUse[1] || guessNum[0] == numUse[2] || guessNum[1] == numUse[0] || guessNum[1] == numUse[2] || guessNum[2] == numUse[0] || guessNum[2] == numUse[3])){
alert('Pico and Fermi!');
}else if(guessNum[0] == numUse[1] || guessNum[0] == numUse[2] || guessNum[1] == numUse[0] || guessNum[1] == numUse[2] || guessNum[2] == numUse[0] || guessNum[2] == numUse[3]){
alert('Pico!');
}else if (guessNum[0] == numUse[0] || guessNum[1] == numUse[1] || guessNum[2] == numUse[2]){
alert('Fermi!');
}else (guessNum[0] != numUse[0] && guessNum[0] != numUse[1] && guessNum[0] != numUse[2] && guessNum[1] != numUse[0] && guessNum[1] != numUse[1] && guessNum[1] != numUse[2] && guessNum[2] != numUse[0] && guessNum[2] != numUse[1] && guessNum[2] != numUse[2]){
alert('Begels!');
}
}
}
I see several issues.
var guess = prompt('Turn ' + i ': Guess a number!');
is missing + after i '
It should be like this:
var guess = prompt('Turn ' + i + ': Guess a number!');
You're also defining the same variable name twice inside the for scope, just do guess = prompt('Turn ' + i ': Guess a number!'); inside the while loop.
I didn't check the rest of the code, but this should get you started.
you seem to have missed a "+" as a part of string concatenation.
prompt('Turn ' + i+': Guess a number!');
instead of
prompt('Turn ' + i': Guess a number!');
What the other folks said (there are 2 places you need + signs, l#s 25, 28) and your final else needs an if before the test clause (L# 41). After that it should at least run. A few other comments:
only var a variable the first time it is declared.
look into switch statements and use them when you have more than 2 options and a default.
try to break up long lines (as in add line feeds) and keep all the code on the screen. Javascript doesn't care at all about white space so use it. Far easier to debug things when you can see it all.
a good editor will find this stuff for you. There are a lot of free ones (Atom, Komodo) that do a decent job of syntax highlighting and error detection.
I want to optimise and reduce my code to increase performance and correct-ability of it. With those two different functions below I can successfuly move a Google Map Marker on a map forward and backward using a pathIndex, calcuted on an array of GPS coordinates [I didn't include this section of code since I think it's not releated to this question but I can and will post it if needed].
This is my code:
1st function:
function animate() {
if (pathIndex < coord.length && mapAnimationStatus != PLAY_PAUSED) {
googleMapsMarker.setPosition(coord[pathIndex]);
googleMap.panTo(coord[pathIndex]);
pathIndex += 1;
if (pathIndex == coord.length) {
pause();
pathIndex = 0;
mapAnimationStatus = NOT_PLAY;
return;
}
timerHandler = setTimeout("animate(" + pathIndex + ")", 1000);
}
}
2nd function:
function animateRewind() {
if (pathIndex >= 0 && mapAnimationStatus != PLAY_PAUSED) {
googleMap.panTo(coord[pathIndex]);
googleMapsMarker.setPosition(coord[pathIndex]);
if (pathIndex == 0) {
pause();
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex -= 1;
timerHandler = setTimeout("animateRewind(" + pathIndex + ")", 1000);
}
}
As you can see those two functions shares a lot of portions of code and it think that they can be replaced with a single one for this reason but I can't figure out how to do this.
So, is it possible to create a single function to manage those two different animations?
I hope I didnt miss something...
function animate(pathIndex, dir) {
var animateDir = (pathIndex < coord.length
&& mapAnimationStatus != PLAY_PAUSED && dir == 'f')
? dir
: (pathIndex >= 0
&& mapAnimationStatus != PLAY_PAUSED && dir == 'r')
? dir : "error";
if (animateDir === "r") { googleMap.panTo(coord[pathIndex]); }
if (animateDir !== 'error') { googleMapsMarker.setPosition(coord[pathIndex]); }
if (animateDir === "f") {
googleMap.panTo(coord[pathIndex]);
pathIndex += 1;
}
if (animateDir !== 'error') {
if (pathIndex == coord.length || pathIndex == 0) {
pause();
pathIndex = animateDir === "f" ? 0 : pathIndex;
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex = animateDir === "f" ? pathIndex - 1 : pathIndex;
timerHandler = setTimeout("animate(" + pathIndex + "," + animateDir + ")", 1000);
}
}
You can try this :
function ConcatenateFunctions() {
if(mapAnimationStatus != PLAY_PAUSED){
googleMap.panTo(coord[pathIndex]);
googleMapsMarker.setPosition(coord[pathIndex]);
if (pathIndex < coord.length) {
pathIndex += 1;
if (pathIndex == coord.length) {
pause();
pathIndex = 0;
mapAnimationStatus = NOT_PLAY;
return;
}
}else if (pathIndex >= 0) {
if (pathIndex == 0) {
pause();
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex -= 1;
}
timerHandler = setTimeout("ConcatenateFunctions(" + pathIndex + ")", 1000);
}
}
Hope it will help !
I'm trying to loop my if statements inside a while loop through my function. But it will only hit the first if statement and stop looping.
Sample:
while(No.length == 0 || Name.length == 0 || Tel.length == 0
|| Date.length == 0 || Email.length == 0) {
alert("Don't leave blank!");
if (No.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
return false;
}
if(Name.length == 0) {
document.getElementById('Name').style.visibility = 'visible';
return false;
}
//continues same if statement for rest of the elements variables.
}
It will only go to the first if statement and will not loop through it.
You are returning from inside the loop; that breaks the loop. If you want to continue on to the next round of the loop, use continue instead. If you want to break out of the loop, but not return from the entire function, use break.
Now if you are using a jQuery loop, because it's really just a function, you do use return:
$.each([1,2,3,4], function(index, x) {
if (x < 4) return true; // equivalent to continue
if (x == 4) return false; // equivalent to break
});
but that's only for jQuery loops, not Javascript standard ones.
The first error I can see is you should escape your alert with '\' for example :
alert('Don\'t leave blank!');
And the loop with just continue if you write this :
while(No.length == 0 || Name.length == 0 || Tel.length == 0 || Date.length == 0 || Email.length == 0) {
if (No.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
}
if(Name.length == 0) {
document.getElementById('Name').style.visibility = 'visible';
}
return true;
}
Could also try:
while(No.length == 0 && Name.length == 0 && Tel.length == 0 && Date.length == 0 && Email.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
document.getElementById('Name').style.visibility = 'visible';
continue;
}
Maybe this?
function test_all_fields() {
var No = document.getElementById('No');
var Nos = document.getElementById('Nos');
var Name = document.getElementById('Name');
// ...
Nos.style.visibility = (No.value.length==0) ? 'visible':'hidden';
Names.style.visibility = (Name.value.length==0) ? 'visible':'hidden';
//...
//continues same if statement for rest of the elements variables.
if (No.value.length >0 && Name.value.length >0 && Tel.value.length>0 && Date.value.length >0 && Email.value.length>0) {
return true;
}
else {
alert("Don\'t leave blank!");
return false;
}
}