first loop stops when the second starts - javascript

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

Related

Javascript: For loop in a for loop

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.

For loop lasts infinitely javascript

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

Why can't I copy a part of my array in Node?

I'm trying to set up an array in which a part is repeated twice. It consists of three articles (in articleArray[0] through articleArray[2]) and for each there's a list of every word in the article (for instance articleArray[1][1] lists each word in that article). I want to clone that last part to articleArray[1][2], but for some reason it won't work? I'm using a for-loop
for (var x=0; x < articleCount; x++) {
for (var y=0; y < articleArray[x][1].length; y++) {
articleArray[x][2] = [];
articleArray[x][2][y] = articleArray[x][1][y];
}
}
After running that, each value in articleArray[1][2] is empty except the last one, for some reason. Why is it not copying my values?
You're repeatedly overwriting articleArray[x][2] with an empty array. You will need to move the line
articleArray[x][2] = [];
one level up, outside of the inner loop:
for (var x=0; x < articleCount; x++) {
articleArray[x][2] = [];
for (var y=0; y < articleArray[x][1].length; y++) {
articleArray[x][2][y] = articleArray[x][1][y];
}
}
Notice that this can be simplified using slice to clone the array:
for (var x=0; x < articleCount; x++) {
articleArray[x][2] = articleArray[x][1].slice();
}
how about this version?
articleArray.forEach(arr => {
arr[2] = arr[1].slice();
});

why is my loop only seeing the value of the first array element?

function Deal()
{
var suffledDeck:Array;
var playerOneCards: Array;
var playerTwoCards: Array;
var first:int =0;
var second:int = 1;
suffledDeck = new Array();
playerOneCards = new Array();
playerTwoCards = new Array();
//var CardLeft:int = Deck.length;
for(var i = 0; i < Deck.length; i++)
{
Debug.Log(Deck.length);
var ranNum = Random.Range(1,Deck.length);
suffledDeck.Add(Deck[ranNum]);
Debug.Log("suffled deck: " + suffledDeck.length);
}
//var halfDeck: int = (suffledDeck.length / 2);
for(var j = 0; j <=26 ; j++)
{
Debug.Log(first);
Debug.Log(second);
playerOneCards.Add(suffledDeck[first]);
playerTwoCards.Add(suffledDeck[second]);
Debug.Log(playerOneCards[first].img);
Debug.Log(playerTwoCards[second].img);
first += 2;
second += 2;
}
}
when i begin to split the array into 2 separate arrays it begins to ignore every element except the first element. the suffleDeck[] has 52 Card objects loaded in and im trying to split the array so that each player can have there own deck.
Console window for debug purpose: http://puu.sh/2dqZm
I believe the problem is var ranNum = Random.Range(1,Deck.length).
ranNum should be generating a random index between 0 to Deck.length - 1 because array indices start at 0 (not 1).
The problem is with these logging statements:
Debug.Log(playerOneCards[first].img);
Debug.Log(playerTwoCards[second].img);
first and second are valid indexes into suffledDeck, but each player's deck only has half as many cards. Try using j as the subscript in both logging statements instead of first or second.
You should also limit your loop to j < 26, not j <= 26. As it is, you are trying to put 27 cards in each player's deck.
because:
Debug.Log(playerTwoCards[second].img);
here second value us 1 while your array contains only one item that is at zero. causing ArgumentoutofRangeException.
so try:
for(var j = 0; j <=26 ; j++)
{
Debug.Log(first);
Debug.Log(second);
playerOneCards.Add(suffledDeck[first]);
playerTwoCards.Add(suffledDeck[second]);
Debug.Log(playerOneCards[j].img);
Debug.Log(playerTwoCards[j].img);
first += 2;
second += 2;
}

Javascript: confused about how nested for loops work

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

Categories