I'm trying to read in a csv string to a 2D array and for some reason it stops when it gets to the second iteration of the first loop.
Here's the Fiddle and the code:
$(document).ready(function(){
var lay = [[]];
document.getElementById("result").innerHTML = value;
bits = value.split(',');
console.log(bits.length);
elm = bits.length/4;
count=0;
console.log(bits[6]); //here it reads but won't assign to the array
for (i=0; i<=elm; i++)
{lay[i]=[];
console.log('i:'+i);
for (j=0; j<=4; j++)
{ console.log('j:' + j);
console.log('count:' + count);;
lay[i][j] == bits[count];
count = count + 1;
console.log('bit value:' + bits[count]);
}
}
console.log(lay[0][0]);
});
The value for the next element reads and displays, but when I try to assign the data to the array it errors out.
Fixed Code
added the redeclaration of the array in the first loop
That made the error go away.
Fiddle
Thanks!
Something wrong with u'r lay array I think.
Is this element set? lay[i][j]
I think I solved it
http://jsfiddle.net/hgm8r/3/
I've made two changes:
Declared the `lay' value outside the loop
var lay = Array();
And updated it at the start of the first loop
lay[i] = Array();
And now it runs without errors.
Related
I am looking for a way to print out a given variable f.ex. the i of a for-loop for each iteration, without it resulting in the entire console being filled with new lines of new values. Is there a console. method for just printing one line, and updating that as we go?
I realise that you could do this by implementing a text-field in your program which you change the with each iteration, but if there is a way of doing this in the console it would be a bit easier (and perhaps quicker? although I am really not sure about that). Thanks in advance.
If there is still confusion about what im asking, what i want is my console to print out:
"i = " i once, and then update the i in that one line, instead of:
i=1
i=2
i=3
1=4
.
.
.
which gets really messy as you go. For the exact example of the i in a for loop, you could get this value from just console.log()'ing the same thing for each iteration, and a number will pop up beside it (in firefox anyway), but i would like to be able to do this with some more useful information.
Option 1: use console.groupCollapsed() and console.groupEnd():
console.groupCollapsed();
for (let i = 0; i < 100; i+= 1) { console.log(`i = ${i}`) }
console.groupEnd();
Option 2: set the values in an array or a string and log the var when the iterations finish:
let valuesToLog = [];
for (let i = 0; i < 100; i+= 1) { valuesToLog.push(`i = ${i}`) }
// see it as an array
console.log(valuesToLog);
// see it as a string, with each value separated by ', '
console.log(valuesToLog.join(', '));
how about JQuery console.clear()?
$(function(){
loop_counter();
});
function loop_counter() {
for (let i = 1; i <= 100; i++){
console.clear();
console.log ("i=", i)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm new to javascript so any help would be greatly appreciated.
What I'm trying to do is cycle through every element in the array and count the number of times the value of an element matches a given condition (even if the value is duplicated).
function loaddata(xml) {
var count = 0;
var i;
var xmlDoc = xml.responseXML;
var z = xmlDoc.getElementsByTagName("group");
if (value1 <= value2) {
for (i = 0; i < (0 + z.length); i++) {
if (z[i].getElementsByTagName("name")[0].childNodes[0].nodeValue == "John") {
count++;
}
}
}
$('#count1').html(count);
};
The count value outputted is too small. I believe the reason for this that the for loop isn't iterating through all elements in the array. When I remove the second if loop and output the count for just the for loop this value is also too small. I believe that the for loop isn't searching through the duplicate elements of the array (i.e. it is ignoring them so that they aren't then fed into the second if loop). Is it possible to specify that the for loop include duplicates?
Do a console.log(z[i].getElementsByTagName("name")) and open your browser's console, and see if that array has data in it.
Then console.log(z[i].getElementsByTagName("name")[0].childNodes) and make sure you have nodes in it.
Also, do you have many <group></group> tags? Because that's what you are selecting with var z = xmlDoc.getElementsByTagName("group");
I hope that helps,
I'm making a typing game. When multiple players play the game it runs through the same set of functions again. I'm using the variable j as a counter to advance words when they are typed correctly. For some reason, on the second pass on each upkeystroke, it logs j = 1 & j = whatever the value of the previous players last word + 1 is. When each player plays, I want each set of words they are typing to be the same, so that it is fair. I can't figure out why this is happening or even how the variable has 2 values at the same time?!?!?
What gives?
Here's the code in question, but there's a bunch of callbacks that could be involved, although the only place this variable is called is inside this function.
//advances ship on correct typing
function runRace() {
timer();
var j = 1;
//BUG HERE !! Works fine on first iteration but on second
//iterations value jumps beteween 1 and whatever the next
//one is. It's like on every keystroke it reassigns var j
//back to 1, then back to the element number it was on
//last time
//!!! j has 2 values !!!it's keeping the value from the
//prior running of run race
$(document).keyup(function(e){
var targetWord = $(".toType").text();
var typedWord = $("#word").val();
//while (j < gameWords.length){
console.log("j = " + j);
if(typedWord === targetWord){
$(".player").css({left: "+=15px",});
targetWord = $(".toType").text(gameWords[j]);
$("#word").val("");
j++;
}else {
return
};
//}
});
}
If you need to see the rest of the code to figure this out, it's here. Eventhough it's not running right on jsfiddle for reason, it works other then the bug, locally https://jsfiddle.net/ujsr139r/1/
As i mentioned in my comment you're creating multiple listeners everytime runRace() is called.
You could try something like this instead (please note, this isn't the best way to do this, i'm just demoing. Global variables like j in this case aren't a clever idea.:
var j=1; // global because its outside of your function
$(function(){
$(document).keyup(function(e){
var targetWord = $(".toType").text();
var typedWord = $("#word").val();
//while (j < gameWords.length){
console.log("j = " + j);
if(typedWord === targetWord){
$(".player").css({left: "+=15px",});
targetWord = $(".toType").text(gameWords[j]);
$("#word").val("");
j++;
}else {
return
};
//}
});
});
//advances ship on correct typing
function runRace() {
j = 1;
timer();
}
I am working on a JS where I want to create a simple game that starts by chosing number of players, name of each player and whether a player is a dealer or not. There can be only one dealer for each game:
function player(playerName, playerDealer) {
this.playerName = playerName;
this.playerDealer = playerDealer;
}
var playerNumber = prompt('Nr of players?');
var playersArray = [];
for (i = 0; i < playerNumber; i++) {
var j = i + 1;
var dealerAssigned = false; // control variable to check whether dealer has been assigned
var inputName = prompt('Name of player nr ' + j);
var inputDealer = prompt('Is player ' + inputName + ' also a dealer? (yes/no)');
playersArray[i] = new player(inputName, inputDealer);
for (k=0;k<playerNumber;k++){ // I want to go through the players array to check if dealer has been assigned
if (playersArray[k].playerDealer == 'yes') {
dealerAssigned=true;
break;
};
};
if(dealerAssigned){ //if dealer has been assigned, don't add the current player to the array and continue with the next iteration
alert("already assigned");
continue;
};
};
I need to include a simple test into the loop that would check if the dealer has been appointed. If so, I want the script only to alert 'already assigned' and skip to the next player. But I am constantly getting the following error
TypeError: playersArray[k] is undefined
Can anybody explain why is it undefined?/What am I doing wrong?
The bug you're specifically asking about appears to me to be that you're iterating over undefined array values, as the error you're getting suggests.
You're getting the number of players you want in line
var playerNumber = prompt('Nr of players?');
Then, you proceed to have two iterations (one nested in the other), in which the inner loop is trying to access values that haven't yet been assigned since the outer loop hasn't gotten there yet:
for (i = 0; i < playerNumber; i++) {
playersArray[i] = new player(inputName, inputDealer);
for (k=0; k < playerNumber; k++) {
if (playersArray[k].playerDealer == 'yes') {
...
}
}
}
It appears to me that the logical error here is the nested loop. I recommend just initializing all players in one loop, then verify that all players have an assigned dealer afterward.
I should add that I'm being intentionally myopic here and focusing very narrowly on the question asked and overlooking other issues I see.
Your for loop inside a for loop is iterating over an array that hasn't been filled yet.
First iteration playersArray[j] = new Player(...) makes the array [Player] or an array of one element! Yet the second loop is looking for an array of many elements. once you look for playersArray[1] but there is only playerArray[0] you get undefined and so undefined.playerDealer causes a TypeError.
`This is your structure stipped-down:
for (i = 0; i < playerNumber; i++) {
playersArray[i] = new player(inputName, inputDealer);
for (k=0;k<playerNumber;k++)...{
//anything with index k > i is undefined, since your outer loop
//hasn't initialized it yet.
}
}
It seems that your i-loop is trying to insert elements for the size of the array to be, but your k-loop is trying to also access the entire array instead of just the initialized portions. Limit this to for (k=0; k<i+1 ;k++) so you only check the previously initialized values of you playersArray
I've got 2dim array set as global variable populated with numbers on row - 0 and strings on row-1.
But when I passed it as a parameter to a function most of its values modifies into undefined but in one strangely value is kept!?!
function formElements(howMany){
elArr = [];
var w; var surface;
for(var j=0; j<howMany; j++){
w = randomNumber(1,200);
surface = w*randomNumber(1,100);
elArr[0] =[j];
elArr[1] =[j];
elArr[0][j]=surface;
elArr[1][j]='_'+j;
}
aFunction(elArr,...other parameters....); //in this function I receive array with these undefined values I mentioned above!!!
}
function randomNumber(x,y) {
return Math.floor((Math.abs(y - x) + 1) * Math.random()) + Math.min(x, y);
}
Could somebody tell me what's wrong?
10x and BR
The references to j make it look like this is inside a loop. In which case, I don't think this is doing what you want:
elArry[0] = [j];
This sets the value of elArray[0] to an array with a single element, j. If you're doing that inside your loop then you're overwriting the arrays every time with a new one with a single element.
EDIT:
And now that you've posted the full loop that's verified. You probably want something like:
function formElements(howMany){
elArr = [[],[]];
for(var j=0; j<howMany; j++){
elArr[0][j]=surface;
elArr[1][j]='_'+j;
}
aFunction(elArr,...other parameters....);
}