Comparing Arrays with nested loops - javascript

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');
}
}

Related

Not understood weird variable behavior in checkers game JavaScript

I'm programming a checkers game for a high school project. I have a weird variable behaviour and I can't figure out why it's happening. Let me show you the code:
var player = 1;
var lastClicked;
var wasClicked = false;
var isEmpty = new Array(8);
for (var i = 0; i < 8; i++) {
isEmpty[i] = new Array(8);
for (var j = 0; j < 8; j++) {
isEmpty[i][j] = true;
}
}
function CreateBoard() {
var board = document.createElement("table");
board.cellSpacing = 0;
for (var i = 0; i < 8; i++) {
var tr1 = document.createElement("tr");
for (var j = 0; j < 8; j++) {
var td1 = document.createElement("td");
td1.setAttribute("id", "td" + i + j);
td1.addEventListener("click", function () { CheckIandJForLater(i, j); });
if (i % 2 == 0) {
if (j % 2 == 0)
td1.style.backgroundColor = "beige";
else
td1.style.backgroundColor = "black";
}
else {
if (j % 2 == 0)
td1.style.backgroundColor = "black";
else
td1.style.backgroundColor = "beige";
}
tr1.appendChild(td1);
}
board.appendChild(tr1);
}
document.body.appendChild(board);
}
function CheckIandJForLater(i, j) { // A function which is meant to show the weird behavior, which prevents me from using function I want to use in the event listener
alert("Function i: " + i);
alert("Function j: " + j);
}
function DeployPieces() {
CreateBoard();
var pieceIndex = 1;
for (var i = 0; i < 8; i++) {
if (i < 3) {
if (i % 2 == 0) {
for (var j = 1; j < 8; j += 2) {
var td1 = document.getElementById("td" + i + j);
var circle1 = document.createElement("span");
circle1.setAttribute("class", "redCircle");
circle1.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle1.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td1.appendChild(circle1);
isEmpty[i][j] = false;
}
}
else {
for (var j = 0; j < 8; j += 2) {
var td2 = document.getElementById("td" + i + j);
var circle2 = document.createElement("span");
circle2.setAttribute("class", "redCircle");
circle2.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle2.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td2.appendChild(circle2);
isEmpty[i][j] = false;
}
}
}
else if (i > 4) {
if (i % 2 == 0) {
for (var j = 1; j < 8; j += 2) {
var td3 = document.getElementById("td" + i + j);
var circle3 = document.createElement("span");
circle3.setAttribute("class", "whiteCircle");
circle3.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle3.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td3.appendChild(circle3);
isEmpty[i][j] = false;
}
}
else {
for (var j = 0; j < 8; j += 2) {
var td4 = document.getElementById("td" + i + j);
var circle4 = document.createElement("span");
circle4.setAttribute("class", "whiteCircle");
circle4.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle4.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td4.appendChild(circle4);
isEmpty[i][j] = false;
}
}
}
}
}
function AlertToPressOnSquare() {
alert("Player " + player + ", please press on the square to which you would like to move the piece");
if (player == 1)
player = 2;
else if (player == 2)
player = 1;
}
function MoveToSquare(i, j) { //The function I want to use in the td1 event listener
if (wasClicked && isEmpty[i][j]) {
var lastClickedId = lastClicked.getAttribute("id");
var lastClickedLocation = lastClickedId[6] + lastClickedId[7];
var v1 = parseInt(lastClickedId[6], 10);
var v2 = parseInt(lastClickedId[7], 10);
var tdFrom = document.getElementById("td" + lastClickedLocation);
var tdTo = document.getElementById("td" + i.toString() + j.toString());
if (lastClicked.getAttribute("class") == "whiteCircle") {
if (v1 == i - 1 && (v2 == j - 1 || v2 == j + 1)) {
tdFrom.removeChild(lastClicked);
tdTo.appendChild(lastClicked);
}
}
else if (lastClicked.getAttribute("class") == "redCircle") {
if (v1 == i + 1 && (v2 == j - 1 || v2 == j + 1)) {
tdFrom.removeChild(lastClicked);
tdTo.appendChild(lastClicked);
}
}
alert("Player " + player + ", please press on the piece you would like to move");
wasClicked = false;
}
}
So, the weird behavior is as follows: Every time I click on a td in the table and run the CheckIandJForLater function, I get the value 8 for both i and j. They should not get these values, as i and j are supposed to be updated in the for loop. Moreover, they should never reach the value of 8, since both the loops run between 0 and 7.
It's also worth noting that if I put alert(i); and alert(j); regularly, without the CheckIAndJForLater function, their values are printed fine.
I really struglle in finding out how to solve this weird behavior. May someone help me? Thank you.
Why is that behavior happening? Is there a solution?

Javascript loop within a loop-only executes first time

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));

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

Javascript: how to remove last comma in for-loop

How can I remove the last comma from this function.
for(var i = 0; i <= 100; i++) {
if(i % 2 === 0) {
div.innerHTML += l + ",";
}
else {
div.innerHTML += " ";
}
}
First, use arrays instead strings for sum strings, its faster.
Second:
var arr = [];
for (var i = 0 ;i <= 100; i+=2) arr.push(l);
dividedThree.innerHTML = arr.join(', ');
function loop {
for (var i = 0; i <= 100; i++) {
if (i % 2 === 0) {
dividedThree.innerHTML += l;
if (i < 100)
{
dividedThree.innerHTML += ",";
}
} else {
dividedThree.innerHTML += " ";
}
}
}
Try using and (&&) condition for 100 and show only i value for 100.
function loop() {
var dividedThree = document.getElementById('MY_ID');
for (var i = 0; i <= 100; i++) {
if (i % 2 === 0 && i !== 100) {
dividedThree.innerHTML += i + ", ";
} else if (i === 100) {
dividedThree.innerHTML += i;
} else {
dividedThree.innerHTML += " ";
}
}
}
loop();
<p id="MY_ID">
<p>
does this version work for you?
function loop() {
var data = '';
for (var i = 0; i <= 49; i++) {
data += l + ',' + ' ';
}
data += l;
dividedThree.innerHTML = data;
}
What are you trying to do? where does 'l' come from?

After pasting the following code, my browser crashed. Why?

After pasting the following code, my browser crashed. I have absolutely no idea why. I am a new to Javascript.
Here is my code:
var randarray = new Array();
var l = 0;
var flag;
var numofpost = 5;
function randomposts(json) {
var total = parseInt(json.feed.openSearch$totalResults.$t, 10);
for (i = 0; i < numofpost;) {
flag = 0;
randarray.length = numofpost;
l = Math.floor(Math.random() * total);
for (j in randarray) {
if (l == randarray[j]) {
flag = 1;
}
}
if (flag == 0 && l != 0) {
randarray[i++] = l;
}
}
document.write('<ul class="rp-menu">');
for (n in randarray) {
var p = randarray[n];
var entry = json.feed.entry[p - 1];
for (k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
var item = "<li>" + "" + entry.title.$t + "</li>";
document.write(item);
}
}
}
document.write('</ul>');
}
The increment of i in your first for loop is behind a condition, so if it never resolves to true, you'll have an infinite loop

Categories