Pot.forEach

{Object|Array|*} Pot.forEach ({Object|Array} object, {Function} callback [, {Object|*} context])
{Pot.Deferred} Pot.Deferred.forEach ({Object|Array} object, {Function} callback [, {Object|*} context])
{Pot.Deferred} Pot.Deferred.prototype.forEach ({Function} callback [, {Object|*} context])

Pot.js と PotLite.js で利用可能。

引数 object の各アイテムに対してイテレートします。

引数 object の各アイテムに対して、引数 callback を実行しながらイテレートします。
処理は、Array.prototype.forEach と同じように実行されます。
引数 context が指定されると、callback 関数の this が context にとって代わります。

コールバック関数の引数は以下のようになります。

function (value, key, object) { this === context }

    value  : {*}              object の各値
    key    : {String|Number|*}  object の各キー
    object : {Object|Array}     object 自身

処理は 同期処理、非同期処理、それぞれ異なります。

  • Pot.forEach は同期処理になります。
    Pot.globalize() 適応済みの場合は forEach() で実行できます。
  • Pot.Deferred.forEach は非同期処理になり、Pot.Deferred のインスタンスを返します。
    Pot.globalize() 適応済みの場合は Deferred.forEach() で実行できます。
  • Pot.Deferred.prototype.forEach は、Pot.Deferred.prototype.async() によって 同期/非同期 が変化します。
    Pot.Deferred チェイン上で実行でき、Pot.Deferred のインスタンスを返します。

callback 関数の中で StopIteration (Pot.StopIteration) を throw することでループを止められます。

Pot.Deferred.forEach.slow() のようにして速度の指定ができます。
非同期では、ほとんどの環境で速度指定が可能ですが、 同期での速度指定は一部の環境 (XUL 上など) のみになります。
指定できる名前は以下の表を参照ください。
デフォルトの速度は normal です。

値 / メソッド名 速度
limp 最も遅い
doze 遅い
slow 遅め
normal 通常
fast 速め
rapid 速い
ninja 最も速い

第一引数の object が返ります。

Pot.forEach で同期処理の例:

// 配列の例
var result = 0;

Pot.forEach([1, 2, 3], function(value, i, array) {
    result += value;
});
debug(result); // 6
// オブジェクトの例
var result = '';

Pot.forEach({a: 'foo', b: 'bar'}, function(value, key, object) {
    result += key + '=' + value + ',';
});
debug(result); // 'a=foo,b=bar,'

Pot.Deferred.forEach で非同期処理の例:

// 配列の例
var result = 0;

Pot.Deferred.forEach([1, 2, 3], function(value, i, array) {
    result += value;
}).then(function() {
    debug(result); // 6
});
// オブジェクトの例
var result = '';

Pot.Deferred.forEach({a: 'foo', b: 'bar'}, function(value, key, object) {
    result += key + '=' + value + ',';
}).then(function() {
    debug(result); // 'a=foo,b=bar,'
});

Pot.Deferred.prototype.forEach で非同期処理の例:

// 配列の例 (1)
var result = 0;

var d = new Pot.Deferred();

d.then(function() {
    return [1, 2, 3];
}).forEach(function(value, i, array) {
    result += value;
}).then(function() {
    debug(result); // 6
}).begin();
// 配列の例 (2)
var result = 0;

var d = new Pot.Deferred();

d.forEach(function(value, i, array) {
    result += value;
}).then(function() {
    debug(result); // 6
}).begin([1, 2, 3]);
// 配列の例 (3)
var result = 0;

Pot.Deferred.begin(function() {
    return [1, 2, 3];
}).forEach(function(value, i, array) {
    result += value;
}).then(function() {
    debug(result); // 6
});
// オブジェクトの例
var result = '';

Pot.Deferred.begin(function() {
    return {a: 'foo', b: 'bar'};
}).forEach(function(value, key, object) {
    result += key + '=' + value + ',';
}).then(function() {
    debug(result); // 'a=foo,b=bar,'
});