Javascript: For loop in a for loop - javascript

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.

Related

How to print a 2d matrix using JS?

I created a sudoku solver in python. I want to display it in a 9X9 grid but don't know how to do it. I think javascript can be used for this, but I don't have much idea about that language. Can someone provide me some suggestions on how to do it?
Bro here i present a code for you in which you can display a 9*9 board in the webpage whose elements are inserted by the user itself. The code starts...
function InputBoard(){
var Board = new Array(9); // Create one dimensional Array
for (var i = 0; i < Board.length; i++) { // create 2D Array using 1D
Board[i] = [];
}
var index = 0;
var s =prompt("Enter Elements");
for (var i = 0; i < 9; i++) {
for (var j = 0; j < 9; j++) { // Initialize 2D array elements
Board[i][j] = s[index++];
}
}
for (var i = 0; i < 9; i++) {
for (var j = 0; j < 9; j++) {
document.write(Board[i][j] + " "); // Display 2D Array
}
document.write("<br>");
}
return Board;
}
InputBoard();

Sum of Primes using Sieve of Eratosthenes can't find bug

I'm working in JavaScript and this is a bit confusing because the code is returning the correct sum of primes. It is working with larger numbers. There is a bug where for 977 it returns the sum of primes for 976, which is 72179, instead of the sum for 977 which is 73156. Everything I've test so far has come back correctly.
function sumPrimes(num) {
var sum = 0;
var count = 0;
var array = [];
var upperLimit = Math.sqrt(num);
var output = [];
for (var i = 0; i < num; i++) {
array.push(true);
}
for (var j = 2; j <= upperLimit; j++) {
if (array[j]) {
for (var h = j * j; h < num; h += j) {
array[h] = false;
}
}
}
for (var k = 2; k < num; k++) {
if (array[k]) {
output.push(k);
}
}
for (var a = 0; a < output.length; a++) {
sum += output[a];
count++;
}
return sum;
}
sumPrimes(977);
The problem stems from the fact that your "seive" Array is indexed from 0, but your algorithm assumes that array[n] represents the number n.
Since you want array[n]===true to mean that n is prime, you need an Array of length 978 if you want the last item to be indexed as array[977] and mean the number 977.
The issue seems to be fixed when I change all instances of < num to < num+1.

Javascript and for loops issue

Is something wrong with my code? I was expecting my code:
years=new Array();
for (i = 0; i < 5; ++i) {
for (j = 1; j < 13; ++j) {
player.push(Math.round( nestedData[i].value[j] ))
}
years.push(player)
}
console.log(years)
to print something like:
[array[12],array[12],array[12],array[12]]
but the result that i get is:
[array[60],array[60],array[60],array[60]]
Create a new player array inside the first for loop. The problem with your code is that the values were being pushed into the same array instance.
var years = [];
for (i = 0; i < 5; ++i) {
var player = [];
for (j = 1; j < 13; ++j) {
player.push(Math.round( nestedData[i].value[j] ))
}
years.push(player)
}
console.log(years)
As an addition to the correct answer already, please use var to declare your variables:
for (var i=0; i < 5; ++i) {
var player = [];
for (var j = 1; j < 13; ++j) {
...
Otherwise, it will use i as a global variable, which could end poorly if you have two functions looping at the same time, e.g.:
function loopone() {
//wouldn't expect this to be an infinite loop eh?
for (i=0; i < 100; i++) {
looptwo();
}
}
function looptwo() {
for (i=0; i < 10; i++) {
}
}

setting a variable to each element of an array

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.

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