What is the main difference between:
var test=[5,6,7,8,9];
$.each(test, function (i, num) {
setTimeout(function(){console.log('i: '+i+' '+num)},500);
});
for (var j = 0; j < test.length; j++) {
setTimeout(function(){console.log('j: '+j+' '+test[j])},500);
}
First loop outputs:
i: 0 5
i: 1 6
i: 2 7
i: 3 8
i: 4 9
Second loop outputs:
5 times 'j: 5 undefined'
I understand why the second loop does this, but not why $.each works 'as expected'
Thanks!
In the first snippet's behind the scene, for every iteration the call back that you have supplied will be called. That means, internally it will create a scope per iteration. That eventually becomes a cloure.
But in the second snippet. The initial scope will be used while the timeout's call back got triggered. So it is displaying that output. And you can make it work by using the following code,
for (var j = 0;j<test.length-1;j++) {
var scope = function(i) {
setTimeout(function(){console.log('j: '+i+' '+test[i])},500);
};
scope(j);
}
Related
for(var i = 1; i<10; i++){
for(var j = 1; j<10; j++){
ss.getRange(j, j).setValue('Second Loop');
}
ss.getRange(i, i).setValue('First Loop');
}
In this example, I'm iterating through two For Loops. The results from the first loop should replace the result from the second loop because it comes after the second loop has set the values of the cell in the Google Sheet.
Yet this is the result that I get:
I sincerely appreciate your response.
see when the outer loop runs last time , then the inner loop overwrites all the existing cells but the last one statement executes and prints first loop
Consider the last iteration of i = 9 which would run like this
for(var j = 1; j<10; j++){
ss.getRange(j, j).setValue('Second Loop');
}
ss.getRange(9, 9).setValue('First Loop');
So the last iteration of the enclosing loop will first write "Second Loop" to all diagonals and after that write "First Loop" to the field (9,9).
Nested loops run in the order in which the enclosing loop is run.
i=1: j=1 -> j=2 -> j=3 -> ... -> j=9
i=2: j=1 -> j=2 -> ... -> j=9
i=3: ...
So for each i, every j is iterated.
I have a assignment for a school project. The task is Write a for loop to log the message “I am love making pizza pies!” 10 times to the console.
Here's my code: I am using google Chrome as my browser
var pizza = '10'
for (var pizza = 0; < I.love.making.pizza; < pizza++) {
if (I.love.making.pizza;) {
pizza++;
}
}
console.log('I Love Making Pizza');
Step by step:
for (var i =0; i<10; i++){ // our loop.
console.log('I Love Making Pizza'); //our loop body
}
i is the variable we are iterating over. It starts at 0 (hence the var i =0 part). And after doing the loop body (the part between curly brackets) it gets increased by 1 (the i++ part which just means i=i+1). We do this as long as i is smaller than 10 (so until i is 9). Since from 0 to 9 there are 10 numbers we execute out loop body 10 times
Alternatively:
for (var i =1; i<=11; i=i+1){ // our loop.
console.log('I Love Making Pizza'); //our loop body
}
Now we go from 1 to 10 including 10 (hence the <=)
for(pizza = 0;pizza <= 10;pizza++){
console.log("I am love making pizza pies!");
}
The code above should do the trick.
I'm kinda new to Javascript and currently going over the book Professional Javascript for Web Developers and I came across this code which uses a break statement to exit the current loop and jump to a label named outermost.
Now I understand what break and labels do but I can't wrap my head around why the value ends up being 55 at the end?
Ok so the for loop with var i will loop 4 times then at 5 it breaks out to label:outermost and same with j so the first iteration i = 4 and j = 4 and num = 2. I guess this part confuses me.. at what point does the code stop. My first instinct if I were to code this from scratch is to have an outside variable and set the condition on that. But with the below code I don't get where the control structure lies and the final value. Appreciate any help or to be pointed in the right direction, thanks.
var num = 0;
outermost:
for (var i=0; i < 10; i++) {
for (var j=0; j < 10; j++) {
if (i == 5 && j == 5) {
break outermost;
}
num++;
}
}
alert(num);
This nested loop is emulating an odometer. i is the 10's digit, j is the 1's digit. Every time the 1's digit changes, num is incremented; at the start of each iteration, num contains the odometer's value.
The loop stops when both i and j are 5. At that point, the odometer would read 55, and that's what is in num.
When i was 0 to 4, the innermost loop is executed 50 times. When i = 5, the innermost loop is executed just 5 times until it reached i==5 && j==5 and jumped out. So it's total of 55 times.
In the code below I'm adding a callback function essentially to a list in a loop.
every Item in the list that I call the call back it will log >>item30
can you please tell me why? Is there a way create a new function() as the call back so
that it can log
item0
item1
item2
item3
item4
and so on .......
......
for (var j = 0 ; j < 30 ; j += 1) {
addThisThingtoList(function () {
console.log( "item" +j );
});
}
This only happens if your function addThisThingtoList() is using asynchronous behavior (like Ajax calls) and thus its callback is called some time later after the for loop has completely run its course and thus it's index value is at the ending value.
You can fix that with a closure that will freeze the loop value separately for each call to addThisThingtoList() like this:
for (var j = 0 ; j < 30 ; j += 1) {
(function(index) {
addThisThingtoList(function () {
console.log( "item" + index);
});
})(j);
}
Working demo: http://jsfiddle.net/jfriend00/A5cJG/
By way of explanation, this is an IIFE (immediately invoked function expression). The variable j is passed to the IIFE and it becomes a named argument to the function that I named index. Then, inside that function, you can refer to index as the value of j that is frozen uniquely and separately for each call to addThisThingtoList(). I could have named the argument index to also be j in which case it would have just overriden the higher scoped j, but I prefer to use a separate variable name to be more clear about what is what.
Here's a good reference on the IIFE concept if you want to read more about it:
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
This is what closure is all about.
When you call the function, it pulls the value of j at the time it's called, not at the time when it was added to the list.
So by the time you start calling the functions, j is already at 30.
It's a classic javascript scope bug. You need to pass in the j variable to your function:
addThisThingToList(function(j) {
console.log("item" + j);
});
As #Smeegs says, "this is what closure is all about."
I guess its to stop browsers getting nailed all the time by duff code but this:
function print(item) {
document.getElementById('output').innerHTML =
document.getElementById('output').innerHTML
+ item + '<br />';
}
function recur(myInt) {
print(myInt);
if (int < 10) {
for (i = 0; i <= 1; i++) {
recur(myInt+1);
}
}
}
produces:
0
1
2
3
4
5
6
7
8
9
10
10
and not the big old mess I get when I do:
function recur(myInt) {
print(myInt);
if (int < 10) {
for (i = 0; i <= 1; i++) {
var x = myInt + 1;
setTimeout("recur("+x+")");
}
}
}
Am I missing something or is this how you do recursion in JS? I am interested in navigating trees using recursion where you need to call the method for each of the children.
You are using a global variable as loop counter, that's why it only loops completely for the innermost call. When you return from that call, the counter is already beyond the loop end for all the other loops.
If you make a local variable:
function recur(int) {
print(int);
if (int < 10) {
for (var i = 0; i <= 1; i++) {
recur(int + 1);
}
}
}
The output is the same number of items as when using a timeout. When you use the timeout, the global variable doesn't cause the same problem, because the recursive calls are queued up and executed later, when you have exited out of the loop.
I know what your doing wrong. Recursion in functions maintains a certain scope, so your iterator (i) is actually increasing in each scope every time the loop runs once.
function recur(int) {
print(int);
if (int < 10) {
for (var i = 0; i <= 1; i++) {
recur(int+1);
}
}
}
Note it is now 'var i = 0' this will stop your iterators from over-writing eachother. When you were setting a timeout, it was allowing the first loop to finish running before it ran the rest, it would also be running off the window object, which may remove the closure of the last iterator.
Recursion is very little restricted in JavaScript. Unless your trees are very deep, it should be fine. Most trees, even with millions of elements, are fairly wide, so you get at most log(n) recursive calls on the stack, which isn't noramally a problem. setTimeout is certainly not needed. As in your first example, you're right that sometimes you need a guard clause to guarantee that the recursion bottoms out.