For Each (array)

From SwiftAPI

Jump to: navigation, search

Contents

C++

For vectors:

#include <vector>
using namespace std;
 
int values[] = {1, 2, 3, 4, 5};
vector<int> a(values, values+5);
 
int x = 0;
for (vector<int>::iterator iter = a.begin(); iter != a.end(); iter++) {
    x = x + *iter;
}
// x == 15

C#

int[] a = new int[] { 1, 2, 3, 4, 5 };
int x = 0;
foreach (int v in a)
{
    x = x + v;
}
// x == 15

Java

Java SE 5.0+:

int[] a = {1, 2, 3, 4, 5};
int x = 0;
for (int v : a) {
    x = x + v;
}
// x == 15

Pre-5.0:

int[] a = {1, 2, 3, 4, 5};
int x = 0;
for (int i = 0; i < a.length; i++) {
    int v = a[i];
    x = x + v;
}
// x == 15

JavaScript

JavaScript 1.6+ (Firefox 1.5+)

developer.mozilla.org

var a = [1, 2, 3, 4, 5];
var x = 0;
for each (var v in a) {
    x = x + v;
}
// x == 15

Prototype, MooTools

prototype mootools

var a = [1, 2, 3, 4, 5];
var x = 0;
a.each(function(v) {
    x = x + v;
});
// x == 15

jQuery

jquery

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

or

var a = [1, 2, 3, 4, 5];
var x = 0;
$.each(a, function() {
    x = x + this;
});
// x == 15

Pre-JavaScript-1.6

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

Objective-C

developer.apple.com

for ( variable in expression ) { statements }
NSArray *a = @[@1, @2, @3, @4, @5];
int x = 0;
for (NSNumber *i in a) {
  x += i.intValue;
}
// x == 15

Perl

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

The $i can be omitted, in which case it uses $_:

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

PHP

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

Python

a = [1, 2, 3, 4, 5]
x = 0
for v in a:
    x = x + v
# x == 15

Ruby

a = [1, 2, 3, 4, 5]
x = 0
a.each do |v|
    x = x + v
end
# x == 15

Swift

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