Fun Stuff > CLIKC
Need help (lots) with Javascript
pwhodges:
--- Quote from: Sorflakne on 20 Aug 2013, 00:05 ---Ok, so it's safe to assume that i=0 by default all the time then?
--- End quote ---
Not necessarily; there are many reasons why one might want to loop (for instance) from the last element to the first, or over only a subset of the elements.
snalin:
Yes, if you want to loop from last to first, you do:
--- Code: ---for(var i = cars.length-1; i >= 0; i--) {
}
--- End code ---
There's a couple of points here that's important too:
- There is no reason other than convention to use the variable name i in the loop. You could do for(var allTheBears = 0; allTheBears < cars.length etc. etc.
- Note that when you loop backwards, you have to start at length-1, while the -1 doesn't show up if you go forwards. I've also used >= on the comparison. Try to figure out why, it'll help you understand what's going on. Remember that if there's 3 elements in the array, they are indexed from 0 to 2 (n elements means indexing from 0 to n-1)
On vars, javascript is a bit wonky. If you haven't defined i anywhere, and then do this:
--- Code: ---console.log(i);
var i;
console.log(i);
i = 5;
console.log(i);
--- End code ---
The two first console.log statements will print "undefined", as i is... not defined. On the other hand, you can write
--- Code: ---i = 5;
console.log(i);
--- End code ---
and get it to print 5 as expected - the "var" statement isn't needed per se (unlike other languages). It is a really good idea to use it, though - it limits the scope of the variable, which is a more advanced topic, but an important one - when you start writing methods, it will show up to bite you in the ass if you don't use it.
Loki:
--- Quote from: snalin on 20 Aug 2013, 00:56 ---There is no reason other than convention to use the variable name i in the loop.
--- End quote ---
That convention being derived from i being the first letter of the word "iterate" (go through, step by step).
(I am mainly commenting so that this thread goes on my "unread replies to your posts" list).
pwhodges:
I suspect that it goes right back to it being the first letter of the group that defined variables starting with those letters (I-N) as being INTEGER rather than REAL in the original Fortran - so i for "integer", before anyone used fancy words like "iteration"!
cesium133:
I know this isn't really related to the thread, but... Oh God, I hate programs that do that in Fortran. "I wonder what this variable is" *goes looking for declaration* "It's not declared!" Implicit None is your friend. :psyduck:
Navigation
[0] Message Index
[#] Next page
[*] Previous page
Go to full version