for loop question

C

cp

in Perl I would write a for loop as :

for $i ( 1..2 ) {
print "<p>$i</p>";
}

which would output:
<p>1</p>
<p>2</p>

In JavaScript I would write:

for (var i=1;i<3;i++) {
...

or is there an easier (or more idiomatic) way?
 
L

Lasse Reichstein Nielsen

cp said:
in Perl I would write a for loop as :

for $i ( 1..2 ) {
print "<p>$i</p>";
}
....
In JavaScript I would write:

for (var i=1;i<3;i++) {
...

or is there an easier (or more idiomatic) way?

There isn't.

There is another use of "for" in Javascript, that is closer to the
Perl version:
for (var x in obj) { ... }
It iterates through the properties of an object. Notice that it
is different from Perl in that the variable "x" is bound to the
*name* of the properties, not the value.

So, in Perl

my @arr = (1,4,7,9);
for $i (@arr) {
print "$i - ";
}

would print "1 - 4 - 7 - 9 - ", while in Javascript

var arr = [1,4,7,9];
for (var i in arr) {
document.write(i+" - ");
}

would write "0 - 1 - 2 - 3 - ". To get the same effect as in Perl, use

var arr = [1,4,7,9];
for (var i in arr) {
document.write(arr+" - ");
}

(I bit me a lot when I started doing Javascript).
/L
 
D

Douglas Crockford

for $i ( 1..2 ) {
print "<p>$i</p>";
}

which would output:
<p>1</p>
<p>2</p>

In JavaScript I would write:

for (var i=1;i<3;i++) {
...

or is there an easier (or more idiomatic) way?

There should be, but there isn't. I don't think that the C control structures
are suitable for a scripting language, but that's all you get in JavaScript.

http://www.crockford.com/javascript/survey.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top