For Each Index (array)

From SwiftAPI

Jump to: navigation, search

Contents

JavaScript

developer.mozilla.org

var a = [1, 2, 3, 4, 5];
var x = 0;
for (var i in a) {
    x += parseInt(i);
}
// x == 10

Perl

@a = (1, 2, 3, 4, 5);
$x = 0;
foreach $i (0 .. $#a) {
    $x = $x + $i;
}
# $x == 10

Perl 5.12+:

@a = (1, 2, 3, 4, 5);
$x = 0;
foreach $i (keys @a) {
    $x = $x + $i;
}
# $x == 10

PHP

$a = array(1, 2, 3, 4, 5);
$x = 0;
foreach($a as $i => $v) {
    $x = $x + $i;
}
// $x == 10

Ruby

a = [1, 2, 3, 4, 5]
x = 0
a.each_index do |i|
    x = x + i
end
# x == 10

Swift

let a = [1, 2, 3, 4, 5]
var x = 0
for i in indices(a) {
    x += i
}
// x == 10
Personal tools