470,648 Members | 1,657 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,648 developers. It's quick & easy.

for loop question

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?

--
cp
Jul 20 '05 #1
2 985
cp <cp****@nospam.pryce.net> writes:
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]+" - ");
}

(I bit me a lot when I started doing Javascript).
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #2
> 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

Jul 20 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

33 posts views Thread by Arthur | last post: by
3 posts views Thread by zeroDoNotYeSpamtype | last post: by
3 posts views Thread by Gustavo Randich | last post: by
22 posts views Thread by Jan Richter | last post: by
3 posts views Thread by nina297 | last post: by
44 posts views Thread by James Watt | last post: by
reply views Thread by warner | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.