Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring two variables in a for loop

Tags:

javascript

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?

like image 352
Celeritas Avatar asked Feb 04 '13 21:02

Celeritas


People also ask

Can you declare variables in a for loop?

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.

Can we use 2 variables in for loop Python?

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.

Can we use 2 variables in for loop in C?

Yes, by using the comma operator. E.g. for (i=0, j=0; i<10; i++, j++) { ... }


2 Answers

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/

like image 194
Benjamin Gruenbaum Avatar answered Oct 15 '22 22:10

Benjamin Gruenbaum


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

like image 21
Fletcher Bach Avatar answered Oct 15 '22 23:10

Fletcher Bach