For Each Index and Element (array)

From SwiftAPI

Jump to: navigation, search

Contents

JavaScript

Prototype, MooTools

prototype mootools

var a = [3, 1, 4, 1, 5];
var x = 0;
var y = 0;
a.each(function(v, i) {
    x = x + i;
    y = y + v;
});
// x == 10
// y == 14

jQuery

jquery

var a = [3, 1, 4, 1, 5];
var x = 0;
var y = 0;
$.each(a, function(i, v) {
    x = x + i;
    y = y + v;
});
// x == 10
// y == 14

Objective-C

developer.apple.com

- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block
NSArray *a = @[@3, @1, @4, @1, @5];
__block int x = 0;
__block int y = 0;
[a enumerateObjectsUsingBlock:^(NSNumber *v, NSUInteger i, BOOL *stop) {
  x += i;
  y += v.intValue;
}];
// x == 10
// y == 14

Perl

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

Perl 5.12+:

@a = (3, 1, 4, 1, 5);
$x = 0;
$y = 0;
while (($i, $v) = each @a) {
    $x = $x + $i;
    $y = $y + $v;
}
# $x == 10
# $y == 14

PHP

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

Python

a = [3, 1, 4, 1, 5]
x = 0
y = 0
for i, v in enumerate(a):
    x = x + i
    y = y + v
# x == 10
# y == 14

Ruby

a = [3, 1, 4, 1, 5]
x = 0
y = 0
a.each_with_index do |v, i|
    x = x + i
    y = y + v
end
# x = 10
# y = 14

Swift

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