Stuck in an infinite for loop. What am I missing here? - javascript

So I have this for loop, I'm stuck in the second one, but If I am, I'd also be stuck in the first one, whats the problem here?
for(var i = 0; i < oldtds.length;i += 3)
{
var oldNameIndex = sameName(oldtds[i].innerHTML, nameList);
if(oldNameIndex != -1)
{
//This means the name already exists
//I need to combine the times, and remove the tr from the table for the second name
//this loop accesses all the times
for(var j = i + 1; j < oldtds.length; j += 3)
{
//This won't quite work, There are colons between them
var timerArray = oldtds[j].innerHTML.split(":");
timerArray.push(oldtds[oldNameIndex + 1].innerHTML.split(":"));
console.log(timerArray);
console.log("this is j " + j);
}
}
}

Related

For-loops and if-statements on cross referenced sheets

I've got 5 sheets - 1 main sheet and 4 sheets for data. The 4 sheets hold a column of W's and L's, and the main sheet has 8 cells to keep track of these - one cell for each # of W's and # of L's. I'm trying to do so with the following script and then calling the methods in the respective cells of the main sheet.
function totalWins(data) {
var win = 0;
for(var i = 0; i < data.length; i = + 1) {
if(data[i][0] = "W") {
win = win + 1;
}
}
return win;
}
function totalLosses(data) {
var loss = 0;
for(var i = 0; i < data.length; i = + 1) {
if(data[i][0] = "L") {
loss = loss + 1;
}
}
return loss;
}
I get the Internal error executing the custom function. error, which means the code takes longer than 30 seconds to run through the column (n = 100) in one of the four sheets. I really can't figure out why it does this. Any help is appreciated!
You need to increment i. Without you assign +1 to i and the loop takes only the first two values and loops forever with i === 1.
for (var i = 0; i < data.length; i = i + 1) {
// ^
or a bit shorter
for (var i = 0; i < data.length; ++i) {
As mentioned in the comments by TheWizEd, you assign a value if the if statement, where you should compare the value
if (data[i][0] === "W") {
// ^^ strict comparison
You placed + at wrong place in your code
for (var i = 0; i < data.length; i = + 1) {
// ^
|____ This makes acts as `+` sign
So in this case you're not actually incrementing your index so you loop keep on running
change to this
for (var i = 0; i < data.length; i += 1) {
// ^
|_____ This acts as `addition`
Or simply use i++
Fixed it by changing the counters win = win + 1 and loss = loss + 1 to win +=1 and loss +=1. Also with the above increments.

Display For Loop Iterations

This is a basic for loop question. If I have a simple for loop such as:
function printMe()
{
for(var i = 0; i < 5; i++)
{
document.getElementById("text").innerHTML = i;
}
};
printMe();
When I call the function, it only prints the last number in the loop 5. But, how can I make it print ever iteration of the loop so the final list is 0, 1, 2, 3, 4, 5
You are constantly overwriting the value of innerHTML because you are using innerHTML = i. This means that when the loop has finished running, the value will be the last value of i.
You want to use += to append i to the existing value, and you might want to add a space after that as well so they aren't glued together.
document.getElementById("text").innerHTML += i + " ";
Which is a shorthand notation for
document.getElementById("text").innerHTML = document.getElementById("text").innerHTML + i + " ";
Thus: get the old value, add the new value, store it once again in innerHTML.
The problem is you are assign i into innerHTML each loop (not append +=), so it is an expected behavior to have the only last output
Try the following will be fine
function printMe()
{
for(var i = 0; i < 5; i++)
{
var innerHTML = document.getElementById("text").innerHTML;
document.getElementById("text").innerHTML += (innerHTML.length <= 0 ? "" : ", ") + i;
}
};
printMe();
and also if you would like to print the 5 also, you have to change the for loop to for (var i = 0; i < 6; i++) or for (var i = 0; i <= 5; i++)
try it on https://jsfiddle.net/v1jnLw23/

JS what is this loop: / break loop notation?

I just came accros this code:
var indx, hash;
loop:
for (var i in config.users) {
if (config.users[i].email === dataValues.email) {
indx = i;
hash = config.users[i].hash;
break loop;
}
}
Is this valid code? what is "loop:" ? It's hard to google 'js loop:' without just seeing the regular for .. in/ while loops
Yes, this valid code.
loop here is label
The labeled statement can be used with break or continue statements. It is prefixing a statement with an identifier which you can refer to.
NOTE: JavaScript has NO goto statement, you can only use labels with break or continue.
var i, j;
loop1:
for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1"
loop2:
for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2"
if (i === 1 && j === 1) {
break loop1;
}
document.write("i = " + i + ", j = " + j + "<br />");
}
}

JavaScript - Rand without repetitions with tmp array

Since two days I have a problem with arrays and conditions in JavaScript.
Could you check my code and give me suggestions what should I correct to run this code without infinite loop?
The list of steps (to clarify my problem) - how this code should work:
1. starting the draw
2. Get random quote -> quote[r_quote] where r_quote is random number
3. If the tmp array is empty, add drawn quote into tmp[j]
4. Get next random quote (step 2)
5. If the tmp is not empty
6. Compare all tmp elements with the new, random quote
7. If the new random quote is unique, add it to tmp[j]
I've currently problem with step 7. When this part of code is uncommented, the loop begins to be processed infinity.
var quote = new Array();
quote[0] = 'AAAAAAAAAA';
quote[1] = 'Lorem ipsum.';
quote[2] = 'BBBBBBBBBB';
quote[3] = 'CCCCCCCCCC';
var numberOfQoutes = quote.length;
var r_quote;
var tmp = new Array();
var j = 0;
console.log("start... ");
for (i = 0; i < 3; i++) {
r_quote = Math.floor(numberOfQoutes * Math.random());
console.log('[Step ' + i + '] \t\nquote[' + r_quote + ']' + ' => ' + quote[r_quote]);
if(tmp.length == 0) {
console.log('\ttmp array is empty. You can append ANY quote.');
tmp[j] = quote[r_quote];
console.log('\t\tAppended: ' + tmp[j]);
console.log(j); // show current tmp array position
j++;
} else {
// add just unique qoute
console.log('\ttmp array is not empty.');
console.log('\tChecking if drawn quotation has already been appended.')
for(k = 0; k < tmp.length; k++) {
console.log("\tk=" + k + "\t" + tmp[k] + "\t<< comparing >>\t" + quote[r_quote]);
if(tmp[k] !== quote[r_quote]) { // this if probably doesn't work
console.log("\t\t[OK] You can append quote.");
console.log(j); // show current tmp array position
console.log('\t\tAssign this quote[' + r_quote + '] => ' + quote[r_quote]);
console.log('\t\tInto tmp[' + j + ']');
/* what's wrong here?
tmp[j] = quote[r_quote]; // I want to add random qoute to new position in array
console.log("Appended: " + tmp[j]);
console.log(k);
j++;
*/
}
}
}
}
The problem is that here:
for(k = 0; k < tmp.length; k++) {
you check whether k < tmp.length, and here:
tmp[j] = quote[r_quote];
j++;
you always add another element to the array, so it's length keeps climbing until you run out of memory

How do I a break a sub for loop without breaking the main for loop in javascript?

I have a for loop and inside that for loop I have another for loop with a condition for break. The problem is that when the sub for loop breaks the top-level loop also does it. So how do I a break a sub for loop without breaking the main for loop in javascript?
Use a break statement, thus:
var i, j, s = "";
for(i = 0; i < 5; ++i) {
s += "\ni = " + i;
for(j = 0; j < 999; ++j) {
s += "\nj = " + j;
if(j === 1) {
break;
}
}
}
Notice that at the end, s contains the result of five iterations of the whole loop, rather than one.
One possible cause for your issue might be an extra misplaced semicolon, thus:
var i, j, s;
s = "";
for(i = 0; i < 5; ++i) {
s += "\ni = " + i;
for(j = 0; j < 10; ++j); {
s += "\nj = " + j;
if(j === 10) {
break;
}
}
}
In the above case, the inner for loop is actually empty, but indentation makes it look as though it contains the following block (which is actually an immediate child of the "outer" loop). This means that the apparent "outer" loop will break on the first iteration.
Another cause might be a typo leading to the incorrect use of assignment vs equality, thus:
var i, j, s;
s = "";
for(i = 0; i < 5; ++i) {
s += "\ni = " + i;
for(j = 0; j < 10; ++j) {
s += "\nj = " + j;
if(i = 5) {
break;
}
}
}
In this situation, in the condition that causes the inner loop to break, the loop variable of the outer loop has been assigned a value that causes the outer loop to finish. Assignment is truthy, so the break will always be hit.
Yet another cause might be a misunderstanding about variable scope in javascript. In other languages, you might be able to do something like this:
var i, s = "";
for(i = 0; i < 5; ++i) {
s += "\nouter = " + i;
if(true) {
var i;
for(i = 0; i < 999; ++i) {
s += "\ninner = " + i;
if(i === 10) {
break;
}
}
}
}
The trouble here is that in javascript, variables are scoped to the function in which they are declared with var. (or global, if outside a function or used without var). This means that the i of the inner loop is actually the same i as the outer loop

Categories