I am facing a really odd problem when executing my JS code. My code execution is not entering a for loop and there are no errors in the console. When I try executing the loop by typing directly in the console, it is executing. Here is the loop :
for(var x = 0; x <= distance; x++) {
var yMinusY1Sq = distance*distance - (x - startX)*(x - startX)
var yMinusy1Cal = parseInt(Math.sqrt(yMinusY1Sq));
console.log(yMinusY1Sq, yMinusy1Cal);
if((yMinusY1Sq == yMinusy1Cal*yMinusy1Cal)) {
y = yMinusY1Cal + startY;
var point = document.createElement("div");
point.className = "output-point";
point.style.height = (grid.offsetHeight/16).toString() + "px";
point.style.width = (grid.offsetWidth/16).toString() + "px";
outputPoints.appendChild(point);
point.style.top = y*oneBoxY;
point.style.left = (x+startX)*oneBoxX;
isodistancePoints.push(point);
}
}
Here, distance is >= 1. The console.log inside the loop is not executing and printing anything. While, if another console.log is put just before the loop, it is printing. So, what is going wrong?
Edit
I tried printing distance, which is a global variable, just before the loop, it is showing undefined, but if it is printed directly using the console, it gives a number value. Here is a screenshot:
Here, is the order of initialization and function, the other global variables initialized are working fine.
var distance;
init();
function init() {
distance = 1;
//Other code
}
$("#run").bind('click', function () {
// some other code
for(var x = 0; x <= distance; x++) {
// some code
}
});
The problem you are facing is in the console. What gets logged is a reference not the value of the object in time. From MDN
Please be warned that if you log objects in
the latest versions of Chrome and Firefox what you get logged on the
console is a reference to the object, which is not necessarily the
'value' of the object at the moment in time you call console.log(),
but it is the value of the object at the moment you open the console.
And the solution is
console.log(JSON.stringify(distance))
or
console.log(`${distance}`)
The problem was that the loop was inside an else statement, and the if of the statement had a local variable named distance. I still don't know the exact cause of the error, as the execution is not supposed to go into the if because its condition is not satisfied, but renaming the variable worked and now I am getting desired output. But if anyone knows the exact reason, please comment.
Related
I have a for loop which will iterate through all choices and and set a value for them.
For some reason, when I run the code it does the first iteration, then skips to the last and does that one 3 times, or so according to the console.
code:
for (i = 0; i < 4; i += 1) {
console.log(i)
var generated = word
while (generated == word) {
generated = wordsJson.characters[Math.floor(Math.random() * wordsJson.characters.length)]
}
choices[i].innerHTML = translate(generated)
}
What I get in console:
0
(3) 3
This is my first time asking something on stackoverflow. If you need more information, please ask.
It appears that the variable i is getting modified outside of the for loop.
Typically you would want to declare your iterator variable (in this case i) so that it's scoped to the loop, which would look like:
for (let i = 0; i < 4; i += 1) { ... }
Note, specifically, the addition of let. Since you haven't done that, it means that either i is already explicitly declared somewhere or, if not, that you've created a new global variable i.
Since you've got code you haven't shown that also seems to relate to i (choices[i]) and methods that we don't know the exact function of (translate()) it's hard to say for certain, but that would be the first place to look.
If not, posting some additional code so we can see the other functionality would be helpful.
I have a block of code that uses Math.random(). I noticed that occasionally the return value would be "Undefined". This is the code I used:
return data.map(val => {
var r = Math.random();
if (r < this.mutChance) {
console.log(Math.random);
debugger;
return this.rDna(val);
}
return val;
});
When i set the mutChance variable to 0 and let the code run for a bit eventually debugger gets called and shows the value of r to be undefined. I tried to reproduce the problem by running in console
var test = Math.random();
while(test){
test = Math.random();
}
However, this loop never ended. I have no idea why the function would act differently within my object, and the console.log(Math.random); Says that the function still has its native code. Nowhere do I override the random function, nor do I use the variable r anywhere else.
I am relatively new to JavaScript and couldn't find this problem anywhere else. The only other code I have imported is the p5.min.js package.
Problem was with how chrome was interpreting the very small values
Without console.log chrome shows it like this
With console.log chrome displays correctly
How to loop through this data: (I have no control over format)
{"rowCount":3,"1":{"K":"2009","V":"Some Data"},"2":{"K":"2010","V":"More Data"}}
Above is a console.log(results) and results is a string
var r = JSON.parse(results);
var t;
for(var i=1;i<=r.rowCount;i++) {
t=r[i].V;
tableData.push(
{title:t, year:'2009', hasChild:true, color: '#000'}
);
}
Error: TypeError: 'undefined' is not an object (evaluating 'r[i].V')
I cannot get it to evaluate the variable i. What am I doing wrong?
Thanks
UPDATE
The incoming data had a bad rowcount causing the error. The accepted answer however is correct... just user error on my part not catching the bad incoming data. Had I put a console.log inside the loop I would have realized the error was actually happening after two successful loops. oops
I assume r.rowCount should be j.rowCount.
Ideally you should also initialise the i variable if you haven't already (i.e. with the var keyword).
(I've also moved the var t declaration outside the loop, to make it clear that it's the same t throughout and you're just changing its value. You shouldn't redeclare it with var each time – although I doubt this affects the output.)
var j = {"rowCount":2,"1":{"K":"name","V":"john"},"2":{"K":"name","V":"sue"}};
var t;
for (var i = 1; i <= j.rowCount; i++) {
t = j[i].V;
console.log(t);
}
Working demo – JSFiddle
I have run in to a stupid problem...
I declared a new variable called leadingZero. I save the modified .js file and run the project with a breakpoint on the leadingZero assignment and in watcher window it says its undefined after passing this line, but all the other declarations here are working fine and I can see the assigned values. needless to say the getObject call does not work now.
var leadingZero = 0; //new variable
var chkActive;
var chkSubscribe;
var hdnItem = getObject('hdnItemCounter');
var ItemCount = parseInt(hdnItem.value) + 1;
for (intCounter = 2; intCounter <= ItemCount; intCounter++) {
chkActive = getObject('dgrProductList_ctl0' + leadingZero + intCounter + '_chkActive');
}
Check this http://jsfiddle.net/DHDsE/
Not getting the undefined problem tho, but having to add toString() to leadingZero for it to render in the console.log, so maybe that's your issue too.
You did set the breakpoint on the line below, didn't you?
Because if you set it on the line var leadingZero = 0; it halts before the line is evaluated, which explains the undefined value in the watcher.
Also, as gillesc pointed out, your leadingZero must be a string, otherwise you're adding up intCounter and leadingZero, rather than concatenating them.
The problem seemed to be changes to the js were not loaded in ie cache. even after closing ie, rebuilding the project and running again, I still need to hit ctrl+f5 on the page to load the new javascript
Here's what I'm trying to achieve:
I have a div that switches between fixed and absolute positioning depending on the scroll position. I have an example that works but I noticed that it's a little slow because it constantly changes the position on each and every pixel of scroll. So I thought that adding an additional if statement (as kind of a on and off switch) would remedy it a bit. But of course it broke.
I rarely use jquery/javascript so to my eyes this seems right but it's not.. any help? Maybe there's even a better way of doing this than if statements.
var top = blah;
var bottom = blah;
var ison=0;
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top && y <= bottom) {
if (ison===0) {
$('#float-contain').addClass('fixed');
var ison = 1;
}
} else {
if (ison===1) {
$('#float-contain').removeClass('fixed');
var ison = 0;
}
}
});
Try removing the "var" inside each if statement like this:
if (y >= top && y <= bottom) {
if (ison===0) {
$('#float-contain').addClass('fixed');
ison = 1;
}
} else {
if (ison===1) {
$('#float-contain').removeClass('fixed');
ison = 0;
}
}
You're already declaring var ison globally above all of this. By redeclaring the variable inside a function you're creating new local instances of it, which causes some undesirable results. I'm not sure if this is you're only problem, but it's definitely part of it.
By the way, here's a good overview of global and local variable in Javascript. They even include an example of identically named global and local variables (which I try to avoid).
I think the slowness is due to repeated document.getElementById calls due to $('#float-contain'). You can cache the jQuery object so that you don't do it. addClass/removeClass/toggleClass doesn't do anything if the element already has/doesn't have the class.
This should work just fine:
var top = blah;
var bottom = blah;
var $elem = $('#float-contain');
$(window).scroll(function (event) {
var y = $(this).scrollTop();
$elem.toggleClass('fixed', (y >= top && y <= bottom));
});
You can also make this code run when the user has finished scrolling instead of running continuously or you can 'throttle' it to run only once per say 100ms. Here's a way to achieve the first technique - http://www.matts411.com/post/delaying_javascript_event_execution/
Most likely the problem is that the value of ison is always undefined when you try accessing it, because you are defining it inside the function, but only after trying to read it.
Whenever you define a variable inside a function, even if it is not declared until later in the code, it automatically overrides any variables with the same name outside the scope - thus inside the function, the value of ison is undefined until it's defined, and the code never reaches that because of your if clauses.
Try removing var from the var ison = n statements inside the function and that may help. This would make it access the variable you declare in global scope.
Here,
if (ison===0) {
$('#float-contain').addClass('fixed');
var ison = 1;
}
Delete the var because you're redeclaring ison with it. (do the same for the other branch).