Javascript loop within a loop-only executes first time - javascript

Please see my js validation function below.
function validate_submit(PassForm) {
var bGo = false;
var rankcount = document.getElementById('rankCount').value;
var j = 0;
var iRankcount0 = document.getElementById('indRankcount0').value;
var iRankcount1 = document.getElementById('indRankcount1').value;
var iRankcount2 = document.getElementById('indRankcount2').value;
var ijs = 0;
var itemp = ijs;
for (i = 0; i < rankcount; i++) {
alert("begin i = " + i);
if (i == 0) {
indRankcount = iRankcount0;
}
else if (i == 1) {
alert('indRankcount: ' + indRankcount);
indRankcount = iRankcount1;
alert('iRankcount1: ' + iRankcount1);
alert('indRankcount: ' + indRankcount);
}
else if (i == 2) {
indRankcount = iRankcount2;
}
alert('before sec loop indRank: ' + indRankcount);
alert('before sec loop itemp: ' + itemp);
for (k = itemp; k < indRankcount; k++) {
alert('in check bGo');
if (document.getElementById("selectedScore" + i + k).checked) {
bGo = true;
j++;
} //if
} //for indRankcount - k loop
if (bGo) {
if (i == 0) {
par = (Math.ceil(indRankcount / 4));
}
else if (i == 1) {
par = (Math.ceil((iRankcount1 - iRankcount0) / 4));
alert('1: ' + par);
}
else if (i == 2) {
par = (Math.ceil((indRankcount2 - iRankcount1) / 4));
}
if (j == par) {
j = 0;
bGo = false;
itemp = indRankcount;
alert("itemp = " + itemp);
continue;
}
else {
alert('25% criteria not met.');
return false;
}
}
else { //else to check bGo
alert('Atleast one box need to be selected.');
return false;
}
j = 0;
bGo = false;
itemp = indRankcount;
alert("loop ends: i =" + i);
} //for rankcount - i loop
res = window.confirm('Are you sure you want to proceed with the selection?');
if (res) {
return true;
}
else {
return false;
}
} //end of validate
Problem is when i=0, it executes fine. But when i=1, second loop (K) doesn't execute(we switched the variable to constant- it works for either itemp or indRankcount.Just one number did it.) It totally skips. Help please! Thank you!

After the inner loop (which uses "k"), there is a "itemp = indRankcount;" line. I guess this cause the issue.
On the first run the "itemp" is 0 so the inner loop step in, but on the second run this value more or equal with the "indRankcount", because you call the code before.
What values are stored in "iRankcount0", "iRankcount1" and "iRankcount2"?
Try to print the "itemp" and "indRankcount" values before the 2. loop.
Updated, try this before the k loop, it will show why the k not starts on the 2. execution.
Console.log(i + "loop:: " + itemp + " val (k first val), " + " indRankcount " + val (k end val));

Related

recursive function returns the same value each time

So I have a checkers game, and I am trying to get it so that you can jump over multiple spaces. It works if you jump the max amount of spaces, but if you don't, say you can jump over two spaces, and you choose to jump over only one, it still removes both pieces even though you only jumped over one of the pieces. I think the problem has is inside the checkForJump() function, and it seems like every time the function is called, it returns the same array, any help would be appreciated.
function checkForJump(buttonSelected, remove, isRoot) {
if(isRoot)
{
clearAvailableMoves();
switchPiece();
}
let adjacentValue = 0;
let jumpNotValid = false;
let RemoveTiles = remove;
for (let i = 0; i < adjacentTileValues.length; i++) {
adjacentValue = adjacentTileValues[i];
if (board.value[adjacentValue + buttonSelected] == enemyPiece && board.value[buttonSelected + (adjacentValue * 2)] == empty) {
if (isSpaceAlreadyInArray(buttonSelected + adjacentValue * 2, i) == false) {
RemoveTiles.push(buttonSelected + adjacentValue);
let tile = new jumpTile(buttonSelected + (adjacentValue * 2));
RemoveTiles.push(buttonSelected + adjacentValue);
console.log("removeTiles" + RemoveTiles);
for (let k = 0; k < RemoveTiles.length; k++) {
tile.tilesToRemove.push(RemoveTiles[k]);
}
console.log("tile.tilesToRemove: " + tile.tilesToRemove);
availableSpaces[i].push(tile);
checkForJump(buttonSelected + (adjacentValue * 2), RemoveTiles,false);
console.log("available spaces = " + availableSpaces);
}
}
}
};
Here is some of the other code, relating to that could also be the source of the problem
function jumpTile(tileID) {
this.tilesToRemove = [];
this.tileID = tileID;
};
let numBlackPieces = 12;
let numWhitePieces = 12;
let adjacentTileValues = [7, 9, -7, -9];
let availableSpaces = [
[],
[],
[],
[]
];
function checkValidSpace(buttonPressed, piece) {
// if button is adjacent to selectedbutton
if (buttonPressed == selectedButton + 7 || buttonPressed == selectedButton + 9 || buttonPressed == selectedButton - 9 || buttonPressed == selectedButton - 7) {
return true;
} else {
let valid = false;
// checks if there is a valid jump
checkForJump(selectedButton,[],true);
// foreach of the possible tiles, if the button pressed is one of them than remove all pieces in that tiles remove list
for (let i = 0; i < availableSpaces.length; i++) {
for (let j = 0; j < availableSpaces[i].length; j++) {
if (buttonPressed == availableSpaces[i][j].tileID) {
valid = true;
console.log("availableSpaces[" + i + j + "] is " + availableSpaces[i][j].tileID + "");
remove(availableSpaces[i][j].tilesToRemove);
return true;
}
}
}
if (valid == false)
return false;
}
}
function checkForJump(buttonSelected, remove, isRoot) {
if(isRoot)
{
clearAvailableMoves();
switchPiece();
}
let adjacentValue = 0;
let jumpNotValid = false;
let RemoveTiles = remove;
for (let i = 0; i < adjacentTileValues.length; i++) {
adjacentValue = adjacentTileValues[i];
if (board.value[adjacentValue + buttonSelected] == enemyPiece && board.value[buttonSelected + (adjacentValue * 2)] == empty) {
if (isSpaceAlreadyInArray(buttonSelected + adjacentValue * 2, i) == false) {
RemoveTiles.push(buttonSelected + adjacentValue);
let tile = new jumpTile(buttonSelected + (adjacentValue * 2));
RemoveTiles.push(buttonSelected + adjacentValue);
console.log("removeTiles" + RemoveTiles);
for (let k = 0; k < RemoveTiles.length; k++) {
tile.tilesToRemove.push(RemoveTiles[k]);
}
console.log("tile.tilesToRemove: " + tile.tilesToRemove);
availableSpaces[i].push(tile);
checkForJump(buttonSelected + (adjacentValue * 2), RemoveTiles,false);
console.log("available spaces = " + availableSpaces);
}
}
}
};
function isSpaceAlreadyInArray(spot, arrayIndex) {
let SpaceAlreadyInArray = false;
for (let j = 0; j < availableSpaces[arrayIndex].length; j++) {
if (availableSpaces[arrayIndex][j].tileID == spot) {
SpaceAlreadyInArray = true;
}
}
return SpaceAlreadyInArray;
}
function clearAvailableMoves() {
for (let i = 0; i < availableSpaces.length; i++) {
availableSpaces[i].pop();
}
}
function remove(removeList, button) {
for (let i = 0; i < removeList.length; i++) {
board.value[removeList[i]] = empty;
board.buttons[removeList[i]].textContent = empty;
if (piece == black) {
numBlackPieces--;
checkForWin(numBlackPieces);
} else if (piece == white) {
numWhitePieces--;
checkForWin(numWhitePieces);
}
}
clearAvailableMoves();
};

javascript Unexpected token else

Someone please help what is wrong in the following code. It is saying "Unexpected token else" while validating javascript code on Java Validate website - esprima.org
`
function add1()
{
var size = 8;
var widthOfGrid = size;
var lenthOfGrid = size;
var linenumber = 1;
for (i = 1 ; i<=size ; i += 1 )
{
for (j = 1 ; j<=size ; j += 1)
{
If (i % 2 === 0)
{
console.log(" " + "#");
}
else
{
console.log("#" + " ");
}
}
}
}
`
In Javascript there is no If statement. Javascript is a case-sensitive language Write it in the lower case - if. And also refactor your code, you have some unused variables.
The problem is that If should be lowercase.
The code should be like this:
function add1() {
var size = 8;
var widthOfGrid = size;
var lenthOfGrid = size;
var linenumber = 1;
for (i = 1; i <= size; i += 1) {
for (j = 1; j <= size; j += 1) {
if(i % 2 === 0)
{
console.log(" " + "#");
}
else
{
console.log("#" + " ");
}
}
}
}
function add1()
{
var size = 8;
var widthOfGrid = size;
var lenthOfGrid = size;
var linenumber = 1;
for (i = 1 ; i<=size ; i += 1 )
{
for (j = 1 ; j<=size ; j += 1)
{
if (i % 2 === 0)
{
console.log(" " + "#");
}
else
{
console.log("#" + " ");
}
}
}
}
working code,you forget make your if in lowercase

curious css setting issue using setInterval

I'm trying to make a palindrome checker that changes the currently compared letters as it recurs.
Essentially, callback will do:
r aceca r
r a cec a r
ra c e c ar
rac e car
My JS Bin shows that the compared letters change green sometimes, but if you run it again, the letters won't change. Why is there a difference in results? It seems to sometimes run in Chrome, more often in FireFox, but it's all intermittent.
Code if needed (also available in JS Bin):
var myInterval = null;
var container = [];
var i, j;
var set = false;
var firstLetter, lastLetter;
$(document).ready(function(){
$("#textBox").focus();
$(document).click(function() {
$("#textBox").focus();
});
});
function pal (input) {
var str = input.replace(/\s/g, '');
var str2 = str.replace(/\W/g, '');
if (checkPal(str2, 0, str2.length-1)) {
$("#textBox").css({"color" : "green"});
$("#response").html(input + " is a palindrome");
$("#palindromeRun").html(input);
$("#palindromeRun").lettering();
if (set === false) {
callback(str2);
set = true;
}
}
else {
$("#textBox").css({"color" : "red"});
$("#response").html(input + " is not a palindrome");
}
if (input.length <= 0) {
$("#response").html("");
$("#textBox").css({"color" : "black"});
}
}
function checkPal (input, i, j) {
if (input.length <= 1) {
return false;
}
if (i === j || ((j-i) == 1 && input.charAt(i) === input.charAt(j))) {
return true;
}
else {
if (input.charAt(i).toLowerCase() === input.charAt(j).toLowerCase()) {
return checkPal(input, ++i, --j);
}
else {
return false;
}
}
}
function callback(input) {
$("#palindromeRun span").each(function (i, v) {
container.push(v);
});
i = 0;
j = container.length - 1;
myInterval = setInterval(function () {
if (i === j || ((j-i) === 1 && input.charAt(i) === input.charAt(j))) {
set = false;
window.clearInterval(myInterval);
container = [];
}
console.log(i + ' : ' + j);
$(container[i]).css({"color": "green"});
$(container[j]).css({"color": "green"});
i++;
j--;
}, 1000);
}
HTML:
<input type="text" id="textBox" onkeyup="pal(this.value);" value="" />
<div id="response"></div>
<hr>
<div id="palindromeRun"></div>
I directly pasted the jsLettering code in the JSBin, but here is the CDN if needed:
<script src="http://letteringjs.com/js/jquery.lettering-0.6.1.min.js"></script>
Change:
myInterval = setInterval(function () {
if (i === j) {
set = false;
window.clearInterval(myInterval);
container = [];
}
console.log(i + ' : ' + j);
to:
myInterval = setInterval(function () {
if (i >= j) {//Changed to prevent infinite minus
set = false;
window.clearInterval(myInterval);
container = [];
}
console.log(i + ' : ' + j);
demo

Comparing Arrays with nested loops

I am trying to compare values of two arrays against each other. If a match is found - do something - else do this.
I put together a fiddle with my code at http://jsfiddle.net/ZvmHx/1/
If you uncomment the second the alert on line 14 you'll see what is wrong. I can't seem to prevent the second alert from firing.
Thanks!
var getkeywords = ["John","Frank","Sarah"];
var captionarray = ["Jim","Joe","Lee","Steve","John","Michelle","Brad"];
for (k = 0; k < getkeywords.length; k++) {
for (l = 0; l < captionarray.length; l++) {
if(getkeywords[k] == captionarray[l]){
alert('Found > ' + getkeywords[k] + ':filter image');
}else{
//alert('not found > ' + getkeywords[k] + ':filter image');
}
}
}
The if/else is being tested for every iteration of your inner loop. I think what you're after is testing if you have a match after the inner loop has run. Something like:
var getkeywords = ["John","Frank","Sarah"];
var captionarray = ["Jim","Joe","Lee","Steve","John","Michelle","Brad"];
var matchFound;
for (k = 0; k < getkeywords.length; k++) {
matchFound = false;
for (l = 0; l < captionarray.length; l++) {
if (getkeywords[k] == captionarray[l]){
matchFound = true;
break;
}
}
if(matchFound){
alert('Found > ' + getkeywords[k] + ':filter image');
}else{
alert('not found > ' + getkeywords[k] + ':filter image');
}
}
I have created a new fiddle:-
http://jsfiddle.net/WZGyy/
var getkeywords = ["John","Frank","Sarah"];
var captionarray = ["Jim","Joe","Lee","Steve","John","Michelle","Brad"];
imagecode = '';
var found=0;
for (k = 0; k < getkeywords.length; k++)
{
for (l = 0; l < captionarray.length; l++)
{
if(getkeywords[k] == captionarray[l])
{
found=1;
break;
}
}
if(found==1)
{
alert('Found > ' + getkeywords[k] + ':filter image');
found=0;
}
else
{
alert('not found > ' + getkeywords[k] + ':filter image');
}
}
Hope that helps..
Before alerting the result you must to compare value with all items in second array
I updated your jsfiddle — try in out http://jsfiddle.net/ZvmHx/5/
var getkeywords = ["John","Frank","Sarah"];
var captionarray = ["Jim","Joe","Lee","Steve","John","Michelle","Brad"];
imagecode = '';
for (k = 0; k < getkeywords.length; k++) {
var isExists = false;
for (l = 0; l < captionarray.length; l++) {
if (getkeywords[k] == captionarray[l]){
isExists = true;
break;
}
}
if (isExists) {
alert('Found > ' + getkeywords[k] + ':filter image');
} else {
alert('not found > ' + getkeywords[k] + ':filter image');
}
}

Trying to add and remove items from an array

The script works by asking user for add or remove an item in the array. Then asks to continue this loop. The problem here is that my script doesn't seem to match my user's input (removeItem) to the item in the list (myList[i]). I'm at a lost as to why this is failing to match.
// new method for removing specific items from a list
Array.prototype.remove = function(from,to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
printList = function() {
var listLength = myList.length;
for (i = 0; i < listLength; i++) {
document.write(i + ":");
document.write(myList[i] + "<br/>");
};
document.write("<br/><br/>");
};
// initial list
var myList = new Array ();
if (myList.length === 0) {
document.write("I have " + myList.length + " item in my list. It is: <br/>");
}
else {
document.write("I have " + myList.length + " items in my list. They are: <br/>");
}
printList();
var continueAdding = "yes";
var askToContinue = "";
while (continueAdding === "yes") {
// loop
var askUser = prompt("What do you want to [A]dd or [R]emove an item to your inventory?").toUpperCase();
switch (askUser) {
case "A": { // add an user specified item to the list
var addItem = prompt("Add something to the list");
myList.push(addItem);
printList();
break;
}
case "R": { // remove an user specified item from the list
var removeItem = prompt("what do you want to remove?");
var listLength = myList.length;
for (i = 0; i < listLength; i++) {
if (removeItem === myList[i]) {
document.write("I found your " + removeItem + " and removed it.<br/>");
myList.remove(i);
}
else {
document.write(removeItem + " does not exist in this list.<br/>");
break;
}
if (myList.length === 0) {
myList[0] = "Nada";
}
};
printList();
break;
}
default: {
document.write("That is not a proper choice.");
}
};
askToContinue = prompt("Do you wish to continue? [Y]es or [N]o?").toUpperCase(); // ask to continue
if (askToContinue === "Y") {
continueAdding = "yes";
}
else {
continueAdding = "no";
}
}
Your loop never allows it to loop through all the items, because it breaks on the first iteration if the item doesn't match.
The break statement should be in the if block, not in the else block - use this instead:
for (i = 0; i < listLength; i++) {
if (removeItem === myList[i]) {
document.write("I found your " + removeItem + " and removed it.<br/>");
myList.remove(i);
break;
}
else {
document.write(removeItem + " does not exist in this list.<br/>");
}
};
if (myList.length === 0) {
myList[0] = "Nada";
}
Also, note that it's looking for an exact match, case sensitive, same punctuation, and everything. If you want it to be a little more lenient you'll need to modify the script to convert both strings to lowercase and strip punctuation before comparing them.
Edit: Just noticed something else -- testing for an empty list needs to be done outside the loop. I updated the above code to reflect this.

Categories