New to Javascript, but I do have experience with Java and Python. I have looked at several other sites to see what's wrong with my code and I know that the error means that the property hasn't been initiated or does not contain anything, but I know I put something in there, so I think I might be getting Java and Javascript mixed up.
Here is my code:
var M=5;
var N=5; //where M and N can be changed if needed
var cellsNotChecked = [];
var startAt = [Math.floor(Math.random()*M), Math.floor(Math.random()*N)];
var path = [startAt];
//then make note of cells visited or not
for(i=0; i<M+2; i++){
cellsNotChecked[i]=[];
for(j=0; j<N+1; j++){
cellsNotChecked[j].push(i>0&&i<M+1&&j>0&&(i!=startAt[0]+1||j!=startAt[1]+1));
}
}
var cellsChecked= 1;
// now keep going until the number of cells checked outweighs the number of cells not checked
while(cellsChecked<cellsNotChecked.length){
//list of potential cells to go to next
var potential = [[startAt[0], startAt[1]+1], //right: y,x+1
[startAt[0],startAt[1]-1], //left: y, x-1
[startAt[0]-1,startAt[1]], //top: (top left hand corner is 0,0, so) y-1, x
[startAt[0]+1,startAt[1]]]; //bottom: y+1, x,
var neighboringCells = [];
//do things
cellsChecked++;
}
The error shows up at var potential = [[startAt[0], startAt[1]+1],... with startAt[0] being underlined all the way to after startAt[1]+1.
Like I said, I think I am giving it values, but I don't know how to check (am using Notepad++).
Edit notes
Added curly braces around first for-loop (thank you for catching that, Mupparthy Ravindranath), but error now occurs at cellsNotChecked[j].push(...).
Full error states: Uncaught TypeError: Cannot read property 'push' of undefined
Part of the problem that I am having is that it appeared to work yesterday before I added a completely un-related function. Now it doesn't work at all. Is it possible for Javascript code to get too long?
Related
I am new to js and hope this is not too trivial, but I am unable to find any help on the net.
I wish to output to console.log and prevent moving to a new line, so the next time the output will be appended to the same line. ie,
"use strict";
for (let i = 0; i<=9;i++){
console.log(i); // here i would like to freeze the output so the result is 0123456789 on one line, rather than those digits in a column.
}
I have seen fixes involving assigning the outputs to a string and printing in 1 hit, but that seems incredibly crude. Even in Fortran 4 as I recall in the '70s, you could prevent moving to a new line before printing again, so I think I am missing something fundamental. Also I cannot find any general help on formatting numerical output in javascript. Can someone point me in the right direction?
Thanks
Unfortunately, the console.log() method will only write out a string to a single line and doesn't support the appending behavior you are looking for.
As you detailed in your original post, you could accomplish writing the final result out through the use of a variable (i.e. displaying the final concatenated string), but not continually appending to the same line within the console itself as the loop is being iterated over.
Alternative Grouping Option
The concept of grouping entries is supported, which is obviously very different than your original ask, but it may be worth considering as mentioned in the documentation for console.group() and might look something like this:
var rollingConcatenation = '';
console.group("Looping Group Example");
for (let i = 0; i<=9;i++){
rollingConcatenation += i;
console.log(rollingConcatenation);
}
console.groupEnd();
This can give your console the following appearance, which can help with readability (depending on your use cases):
Do It Yourself Implementation
Another option might be to store your current console value within a variable and at clear it and rewrite the updated values out. Depending on your very specific use cases, you could achieve the behavior you are looking for using something like this crude implementation:
// Define a custom console
var customConsole = {
// Store a reference to your backing value
tempValue: '',
// Always write out the most recent value
log: function(msg) {
this.tempValue += msg;
console.clear();
console.log(this.tempValue);
},
// A clear method to clear the backing console
clear: function() {
this.tempValue = '';
console.clear();
}
}
for (var i = 0; i < 10; i++) {
// Use your custom console instead of the normal one
customConsole.log(i);
}
Take a new variable outside the loop and then prepare that string inside the loop and then you can console.log() outside the loop.
var str = '';
for (let i = 0; i <= 9; i++) {
str += i;
}
console.log(str);
I've been having problems with my code in JavaScript again. Here is the part of the code that I'm having trouble with and an explanation:
loadThis.onclick = function(){
localStorage.setItem("myName", storedTemporary[i].name);
}
deleteThis.onclick = function(){
this.parentNode.parentNode.remove();
storedTemporary.splice(storedTemporary[i], 1);
}
It splices it from the array and removes it from the screen. But let's say you have 3 items you delete the one and top and the bottom, when you try and load the last one in between it gives an error saying it can't setItem because it "cannot read property undefined". But the interesting thing is that when you console.log the current value of the localStorage item, "myName", it shows the last item's name. This is the for loop. I am using block scoping for it :
var storedTemporary = JSON.parse(localStorage.getItem("temporaryArray"))
for(let i = 0; i < storedTemporary.length; i++)
{
}
I am very confused. Please help.
Thank you,
Scratch Cat
I have looked everywhere I can think of for anything that can provide an answer to this. First time posting a question here - I can usually find my answers. I have a for loop that is pulling information from a range of data that is formatted in one cell like this: 09/01/2016 - Status changed to active.
The loop is supposed to first see how many values are in that column then go one by one and split the data into a simple array, post it into two columns on a separate sheet, then move onto the next one. The problem is that it stops after the first entry.
var numEntries = dataSheet.getRange(1,i+1,1000).getValues();
var lastEntry = numEntries.filter(String).length;
if (lastEntry == 7) {
// no change data to date
sheet.getRange(18,3).setValue("No changes yet");
} else {
var changeData = dataSheet.getRange(8,i+1,lastEntry-7).getValues();
for (var y = 0; y < changeData.length; y++) {
var changeHistory = changeData[y][y].split(" - ");
sheet.getRange(nextRow+1,2).setValue(changeHistory[0]);
sheet.getRange(nextRow+1,3).setValue(changeHistory[1]);
nextRow++;
Logger.log(nextRow);
Logger.log(changeData.length);
Logger.log(y);
}
}
I know that it is executing properly because it is properly setting the "No changes yet" value when there are no entries. Variable nextRow starts at a value of 17, and the log properly shows changeData.length with the number of entries and y being equal to 0. But then it stops. It doesn't follow the loop that y is still less than changeData.length. Any help is very much appreciated!
[edit] - I also want to point out that it does properly split and populate the first value into the two cells I want it to, so the whole for statement does work, it just doesn't loop. [edit]
[16-09-29 15:37:48:514 CDT] 18.0 [16-09-29 15:37:48:515 CDT]
11.0 [16-09-29 15:37:48:515 CDT] 0.0
changeData is an n*1 Array.
You are increasing y and and you are also trying to get the y-th column from changeData.
After the first iteration this is undefined because there's only one column.
undefined does not have a split method throwing an exception and terminating the script. (You may not see this exception, these kinds of exceptions aren't always shown to the user for some reason)
Try
var changeHistory = changeData[y][0].split(" - ");
instead.
I am currently building a small web application with similar functionality across all modules. I want to code small generic functions so that all programmers next to me, call these functions and these functions return necessary but important data for them to implement their functionality. In this example, I am trying to deal with the typical "choose true or false" exercise. So from the template.php they call this function:
function checkAnswers(){
var radiobuttons = document.form1.exer1;
var correctAnswers = answers(); //this is an array of string
var checkedAnswers = checkExerciseRB(radiobuttons, 2, correctAnswers);
for(i=0; i<checkedAnswers.length; i++){
alert(checkedAnswers[i]);
}
}
Function checkExerciseRB is my generic function, it is called from checkAnswers.
function checkExerciseRB(rbuttons, opciones, correct){
var answers = new Array();
var control = 0;
for(i=0; i<rbuttons.length; i++){
var noPick="true";
for(j=0; j<opciones; j++){
if(rbuttons[control+j].checked){
if(rbuttons[control+j].value==correct[i]){
answers[i]= 1;
noPick="false";
break;
}
else{
answers[i]=2;
noPick="false";
break;
}
}
}
if(noPick=="true")
answers[i]=0;
control=control+opciones;
}
return answers;
}
It works great but while looking at my favorite browsers (FireFox, Chrome) error log it says:
TypeError: rbuttons[control + j] is undefined
Any clue on how to deal with this matter?
This probably means that control + j is greater than or equal to the length of the array rbuttons. There's no such array element as rbuttons[control + j].
You should learn how to use the JavaScript debugger in your favorite browsers! Debuggers are great. They let you watch this code run, line by line, as fast or as slow as you want, and watch how the value of control changes as you go.
You’ll watch it, and you’ll think “Oh! That line of code is wrong!”
You're looping through rbuttons.length times, but in each loop you're adding 2 to control. Using control to index your array, you're going to run past the end.
Does the index specified by control + j exist in the array? i.e: If that evaluates to 4, is there at least 5 items in the array?
Also, you should be using var i, var j, etc inside your for loop. Without it your variables are leaking into the scope this code is executed in (most likely the global scope, and that's not good) :)
I have been working with javascript lately and I am using Chrome (12) Developer tools and I have been getting the error:
TypeError: Cannot call method 'getSize' of undefined.
I have no idea of why this is happening but have isolated the part which seems to be the problem:
x = 0;
for(var i=0; i<w; i++){
for(var j=0; j<h; j++) {
display.blit(tile[world[x]], [(i * 34), (j * 34)])
x++;
}
}
the x++; give me the error and when I comment out the code (of x++;) chrome says there are no errors. Display.blit(tile[world[x]], [(i * 34), (j*34)] doesn't seem to have anything to do with the error although I may be wrong.
My question is how to fix this error and why it is happening in the first place.
The problem seems to be that your x exceeds the number of entries you have in your array. So as the entry is undefined you pass it along to your function where you call the getSize method which doesn't exist for undefined.
Without the rest of the script and the values that world and tile have it's hard to say where you went wrong but I would suggest you confirm that there is an entry for each of the calls you are making. If you do know how many entries you have just try alert(x) to see at which x value you get the error.