r/learnjavascript • u/wbport1 • 10d ago
Code quits before creating a 2-d array
I am trying to add a feature to a webpage that simulates an election. "bordaTally" is defined as new Array(); in the second copied text below. "alert 0" is the only one that shows.
Thanks in advance.
function bordaItem(name) {
this.name = name;
this.total = 0;
this.tally = new array();
}
if (document.tournform.rr2[4].checked == true) { //Borda count
for (i=0;i < n; i++) {
alert("alert 0");
bordaTally[i] = new bordaItem(i);
alert("alert 1");
for (j=0; j < n;j++) {
alert("alert 2");
bordaTally[i][j].tally = 0; }
}
for (i=0; i < totBallots; i++)
for (j=0; j < n; j++)
break; //placeholder for now
} //End Borda Count3
u/gimmeslack12 helpful 10d ago
this.tally = new array();
This is incorrect. Try new Array or more simply just [].
2
u/Discordbothost 8d ago
yep that lowercase array is the first crash — constructors are case sensitive so it has to be new Array() or just []. once that runs, the next landmine is bordaTally[i][j].tally like the other comment said; that should be bordaTally[i].tally[j]. hit f12 and the console will name the exact line instead of just stopping after alert 0.
2
u/CelebrityChess 10d ago
the other thing that'll bite you once the array typo is fixed is the line inside the loop, bordaTally[i][j].tally = 0. bordaTally[i] is a bordaItem object, so it has no [j] and that will throw a "cannot set properties of undefined" error as soon as it runs. you want bordaTally[i].tally[j] = 0 instead. you could also just build it up front in the constructor with new Array(n).fill(0) so you don't need the inner loop at all. and if the alerts stop showing again, open the browser console with F12 because the error message there will point at the exact line.