ES5で追加されたJavaScriptのforEach
by kazu69
ECMA-262の第5版(ES5)のまとめ記事見てたらArrayオブジェクトにforEachが追加されてた。
ということで、個人的なメモ。
array.forEach(callback[, thisObject]);
配列の各要素にたいしてcallback関数を実行できます。
thisObjectは、callbackを実行時にthisとして使用するオブジェクト。
さらにECMA-262に対応してないブラウザにはprototypeで拡張してやればネイティブのメソッドとして使える。
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
ということで、サンプル