Why do nested for loops work in the way that they do in the following example:
var times = [
["04/11/10", "86kg"],
["05/12/11", "90kg"],
["06/12/11", "89kg"]
];
for (var i = 0; i < times.length; i++) {
var newTimes = [];
for(var x = 0; x < times[i].length; x++) {
newTimes.push(times[i][x]);
console.log(newTimes);
}
}
In this example I would have thought console.log would give me the following output:
["04/11/10"]
["86kg"]
["05/12/11"]
["90kg"]
["06/12/11"]
["89kg"]
However, I actually get this:
["04/11/10"]
["04/11/10", "86kg"]
["05/12/11"]
["05/12/11", "90kg"]
["06/12/11"]
["06/12/11", "89kg"]
Is anyone able to help me understand this?
EDIT:
Thanks for all your responses!
You are redefining newTimes on every single loop and you are outputting to the console on each column push.
var times = [
["04/11/10", "86kg"],
["05/12/11", "90kg"],
["06/12/11", "89kg"]
];
var newTimes = [];
for (var i = 0; i < times.length; i++) {
for(var x = 0; x < times[i].length; x++) {
newTimes.push(times[i][x]);
}
}
console.log(newTimes);
Returns: ["04/11/10", "86kg", "05/12/11", "90kg", "06/12/11", "89kg"]
http://jsfiddle.net/niklasvh/SuEdt/
// remember that the increment of the counter variable
// is always executed after each run of a loop
for (var i = 0; i < n; i++) {
// some statement(s) to do something..
// initializes child-loop counter in the first run of the parent-loop
// resets child-loop counter in all following runs of the parent-loop
// while i is greater than 0 and lower than n
for (var j = 0; j < p; j++) {
// some statement(s) to do something..
// initializes grandchild-loop counter in the first run of the child-loop
// resets grandchild-loop counter in all following runs of the child-loop
// while j is greater than 0 and lower than p
for (var k = 0; k < q; k++) {
// some statement(s) to do something..
// or add more internal loop-nestings if you like..
}
}
}
// if the counter variables of the descendent-loops were set before the loop-nesting,
// the inner loops would only run once, because the counter would keep the value
// of the abortion condition after the loop is finished
Do this:
var newTimes = [];
for (var i = 0; i < times.length; i++) {
for(var x = 0; x < times[i].length; x++) {
newTimes.push(times[i][x]);
console.log(newTimes);
}
}
You are re-initializing newTimes each time through the loop.
You output would be appropriate if the log statement would read
console.log(times[i][x]);
Instead you output your complete new list newTimes which is initialized outside the inner loop and grows with each inner loop iteration.
The problem is in the second round of the inner loop, where it pushes the second element into newTimes. Anyway I don't understand the reason of inner loop. You can write much simpler:
var times = [
["04/11/10", "86kg"],
["05/12/11", "90kg"],
["06/12/11", "89kg"]
];
for (var i = 0; i < times.length; i++) {
console.log(time[i][0]);
console.log(time[i][1]);
}
Related
I have a function like below:
function launching() {
let ranges = document.getElementsByClassName('range');
liczba2 = 0;
console.log(ranges);
let czeks = document.getElementsByClassName('check');
liczba = 0;
eluwina = 0;
for (let i = 0; i <= czeks.length; i++) {
if (czeks[i].checked) {
liczba ++;
console.log(liczba);
}
}
for (let n = 0; ranges.length; n++) {
let val = ranges.getAttribute('value');
console.log(val);
}
}
The first for loop works fine. However the second one:
for (let n = 0; ranges.length; n++) {
let val = ranges.getAttribute('value');
console.log(val);
}
Doesn't work at all. Even if there's just console log after first loop, it won't execute. I'll be grateful if anyone could help me. Thanks in advance :).
The second loop should be:
for (let n = 0; n < ranges.length; n++) {
let val = ranges[n].getAttribute('value');
console.log(val);
}
In your code, if ranges.length == 0, the loop will end immediately, since the condition ranges.length is falsey. Otherwise it will be cause an infinite loop, because the value of ranges.length doesn't change, and a non-zero value is truthy.
However, the loop will stop because ranges.getAttribute('value') will get an error. ranges is a NodeList, not a single element, and it doesn't have a getAttribute() method. You need to index it to get the current element in the iteration.
I'm doing a scoring app as practice, and I'm trying to get an object to calculate the total score for a player. Here is the part I'm struggling with:
totalScore: function () {
"use strict";
debugger;
var sum = 0;
for (var i = 0; i < this.players[i].length; i++) {
for (var n = 0; n < this.players[i].score[n].length; n++) {
sum += this.players[i].score[n];
}
this.players[i].totalScore = sum;
} }
So I have a main object scoreTable. players is an array of objects which includes another array called score. So what I'm trying to do is create a totalScore object function that runs a loop through the players array that loops on each score array and finds the sum of that array.
I don't know why, but when I run through it on the dubugger, it goes into the first for loop, finds the first array of players, then just skips to the end of the function without running the next loop. I'm not sure why it's doing that.
for (var i = 0; i < this.players[i].length; i++) {
for (var n = 0; n < this.players[i].score[n].length; n++)
}
This should be:
for (var i = 0; i < this.players.length; i++) {
for (var n = 0; n < this.players[i].score.length; n++)
}
Try following:
totalScore: function () {
for (var i = 0; i < this.players.length; i++) {
var player = this.players[i];
player.totalScore = 0;
for (var n = 0; n < player.score.length; n++) {
player.totalScore += player.score[n];
}
}
}
This fixes not only syntax errors, but also the sum-logic itself: sum variable from initial post won't reset for each new player in the top-level loop.
I have a problem in my code:
var row = ["1","2","3","4","5"];
var column = ["1","2","3","4","5"];
var arrayLength = row.length;
var arrayLength2 = column.length;
for (var i = 0; i < arrayLength; i++) {
for (var e = 0; e < arrayLength2; e++) {
var samples = document.querySelectorAll('[data-row-id="'+row[i]+'"][data-column-id="'+column[e]+'"]');
for(var i = 0; i < samples.length; i++) {
var sample = samples[i];
sample.setAttribute('data-sample-id', row);
console.log("Colore cambiato");
}
}
}
When i run it, the cycle lasts infinitely and the console.log is called up a lots of times
Where is the error? Thanks!
The problem is that your inner-most loop uses the same i looping variable as your outer most loop and it's constantly changing i so that the outer loop never finishes.
Change the variable on your inner loop to a different identifier that you aren't already using in the same scope.
Youre using same loop i twice nested so it runs infinitely coz it always resets i in inner loop
use something else instead like k
for(var k = 0; k < samples.length; k++) {
var sample = samples[k];
sample.setAttribute('data-sample-id', row);
console.log("Colore cambiato");
}
I want to use a for loop in another for loop to get the content of an xml file.
The problem is that when the second loop starts the first one stops.
javascript code:
var x = xmlDoc.getElementsByTagName('usr');
for (i=0; i <= x.length; i++) {
var y = x[i].childNodes;
for(n=0; n <= y.length; n++) {
var z = y[n].childNodes[0];
document.write(z.nodeValue);
}
}
xml code:
<usr><age>30</age><location>uk</location></usr>
<usr><age>25</age><location>usa</location></usr>
And the output is:
30uk
It should be 30uk25usa
In both of your loops, you will iterate one too many times.
i=0; i<=x.length should be i = 0; i < x.length and same for the inner loop.
Iterating one too many times generates an error, which breaks the execution
Try storing the total result that you want outside of the first loop, and then use document.write() after the outer loop completes:
var x = xmlDoc.getElementsByTagName('usr');
var zTotal = '';
for (i=0; i < x.length; i++) {
var y = x[i].childNodes;
for(n=0; n < y.length; n++) {
var z = y[n].childNodes[0];
zTotal += z.nodeValue;
}
}
document.write(zTotal);
i have function:
function getFieldNames(arrayOfRecords) {
var theStuff;
for (var i = 0; i = arrayOfRecords.length - 1; i++){
theStuff = arrayOfRecords[i];
theList = theStuff.split('" ');
for (var j = 0; j = theList.length - 1; j++) {
var v = theList[j].split('="');
fName1[i][j] = v[0];
}
}
return fName1;
}
the argument arrayOfRecords is an array, and i dont know how to setup to the 'theStuff' variable an array element? When I do like it is above, i get something stupid.
can anyone help me? :)
There may be other problems but the one that leaps out at me is your for loop header:
for (var i = 0; i = arrayOfRecords.length - 1; i++)
The second part should be a condition, which when evaluated to false will stop the loop from running. What you probably wanted was:
for (var i = 0; i < arrayOfRecords.length; i++)
So when i is not less than arrayOfRecords.length, the loop will stop. Alternatively (to keep the - 1, but I tend to use the above version):
for (var i = 0; i <= arrayOfRecords.length - 1; i++)
The same goes for the nested loop.