Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > for loop question

Reply
Thread Tools

for loop question

 
 
cp
Guest
Posts: n/a
 
      01-22-2004

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
 
Reply With Quote
 
 
 
 
Lasse Reichstein Nielsen
Guest
Posts: n/a
 
      01-22-2004
cp <(E-Mail Removed)> 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 - http://www.velocityreviews.com/forums/(E-Mail Removed)
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
 
Reply With Quote
 
 
 
 
Douglas Crockford
Guest
Posts: n/a
 
      01-23-2004
> 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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Triple nested loop python (While loop insde of for loop inside ofwhile loop) Isaac Won Python 9 03-04-2013 10:08 AM
newbie question: for loop within for loop confusion takayuki Python 17 06-17-2008 09:49 PM
newbie: for loop within for loop question takayuki Python 2 06-16-2008 03:22 AM
while loop in a while loop Steven Java 5 03-30-2005 09:19 PM
Loop the loop... =?Utf-8?B?VGltOjouLg==?= ASP .Net 2 02-16-2005 12:21 PM



Advertisments