For Each Value (associative array)

From SwiftAPI

Jump to: navigation, search

Contents

C++

#include <map>
#include <string>
using namespace std;
 
map<string, int> a;
a["foo"] = 10;
a["bar"] = 20;
a["baz"] = 30;
 
int x = 0;
map<string, int>::iterator cur, end;
for(cur = a.begin(), end = a.end(); cur != end; cur++) {
    x = x + cur->second;
}
 
// x == 60

Java

import java.util.Map;
import java.util.HashMap;
 
Map<String, Integer> a = new HashMap<String, Integer>();
a.put("foo", 10);
a.put("bar", 20);
a.put("baz", 30);
 
int x = 0;
for(Integer v : a.values()) {
    x = x + v;
}
// x == 60

JavaScript

JavaScript 1.6+ (Firefox 1.5+)

Mozilla

var a = {'foo': 10, 'bar': 20, 'baz': 30};
var x = 0;
for each (var v in a) {
    x = x + v;
}
// x == 60

Pre-JavaScript-1.6

var a = {'foo': 10, 'bar': 20, 'baz': 30};
var x = 0;
for (var k in a) {
    var v = a[k];
    x = x + v;
}
// x == 60

Perl

%a = ('foo' => 10, 'bar' => 20, 'baz' => 30);
$x = 0;
foreach $v (values(%a)) {
    $x = $x + $v;
}
# $x == 60

PHP

$a = array('foo' => 10, 'bar' => 20, 'baz' => 30);
$x = 0;
foreach($a as $v) {
    $x = $x + $v;
}
// $x == 60

Python

docs.python.org

a = {'foo': 10, 'bar': 20, 'baz': 30}
x = 0
for v in a.itervalues():
    x = x + v
# x == 60

Ruby

a = {"foo" => 10, "bar" => 20, "baz" => 30}
x = 0
a.each_value do |v|
    x = x + v
end
# x == 60

Swift

let a = ["foo": 10, "bar": 20, "baz": 30]
var x = 0
for v in a.values {
    x = x + v
}
// x == 60
Personal tools