Is it possible to declare two variables in the initialization part of a for loop? I want to call a function on each character of a string.
for(var i = 0, c = aString.charAt(i); i < aString.length; i++){//problem here: not itterating alert("c: "+c) func1[typeOfChar(c)]++ }
The problem is the string isn't being itterated in the sense c
is always the first letter of the string. The alert
was just for trouble shooting purposes, by the way.
I'm curious, how come c
doesn't need the var
keyword when being declared?
UPDATE: got it working. I wasn't going to ask but I notice edits are still being made, I'm used to not using the semi-colons as they are optional. How can a for loop be written without them? I don't add them because I see it as the less the simpler, or do they improve readability?
Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
The use of multiple variables in a for loop in Python can be applied to lists or dictionaries, but it does not work for a general error. These multiple assignments of variables simultaneously, in the same line of code, are known as iterable unpacking.
Yes, by using the comma operator. E.g. for (i=0, j=0; i<10; i++, j++) { ... }
You'd like c
to change at every iteration, not to declare it at the start of the loop, try
var i,c; for(i = 0,c=aString.charAt(0); i < aString.length; ++i, c = aString.charAt(i)){ alert("c: "+c) func1[typeOfChar(c)]++ }
For what it's worth I don't think it makes very readable code, I would put it in the first line.
Here is some information on the comma operator you're using.
Also note that javascript has no block scoping for for loops, so you're actually declaring i
and c
at the top of the current scope (this is usually the top of the current function, or the top of the global scope).
Here is a fiddle: http://jsfiddle.net/maWua/
Simple way to include multiple incrementing variables in a for loop without nesting. This example declares 3 variables.
for (var i = 0, j = 1, n = 2; i < 50, n < 50; i = i + 3, j = j + 3, n = n + 3){ console.log("variable i: " + i); console.log("variable j: " + j); console.log("variable n: " + n); }
see codepen here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With