LL でリスト/配列をループ処理する時のイディオム

Tomohiro wrote this on Apr 7, 2011

リスト/配列の値を順番に評価する

PHP (Array)

<?php
$l = array('foo', 'bar', 'baz');
foreach ($l as $v) {
    /* do something */
}

Perl (Array)

my @l = qw/foo bar baz/;
foreach my $v (@l) {
    # do something
}

Ruby (Array)

l = %w[foo bar baz]
l.each do |v|
  # do something
end

Python (list)

l = ['foo', 'bar', 'baz']
for v in l:
    # do something

JavaScript (Array)

var l = ['foo', 'bar', 'baz'];
for (var i = 0; i < l.length; i++) {
    /* do something */
}

リスト/配列のインデックスと値を順番に評価する

PHP (Array)

<?php
$l = array('foo', 'bar', 'baz');
foreach ($l as $i => $v) {
    /* do something */
}

Perl (Array)

my @l = qw/foo bar baz/;
foreach my $i (0..$#l) {
    # do something
}

Ruby (Array)

l = %w[foo bar baz]
l.each_with_index do |v, i|
  # do something
end

Python (list)

l = ['foo', 'bar', 'baz']
for i, v in enumerate(l):
    # do something

JavaScript (Array)

var l = ['foo', 'bar', 'baz'];
for (var i = 0; i < l.length; i++) {
    /* do something l[i] */
}

References