Prototype-enum-inject
提供:Dev Guides
プロトタイプ-Enumerable inject()メソッド
このメソッドは、反復子の連続した結果に基づいて結果値を増分的に構築します。 これは、配列の構築、数値の合計/平均などに使用できます。
オプションのコンテキストパラメータは、イテレータ関数がバインドされるものです。 使用する場合、イテレータ内の_this_キーワードは、引数で指定されたオブジェクトを指します。
構文
Iterator.inject(accumulator, context);
戻り値
累積値を返します。
例
<html>
<head>
<title>Prototype examples</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script>
function showResult() {
alert("Test1: " + $R(1,10).inject(0, function(acc, n) {
return acc + n;
}) );
//Returns 55 (sum of 1 to 10)
alert("Test2: " + $R(2,5).inject(1, function(acc, n) {
return acc * n;
}) );
//Returns 120 (factorial 5)
}
</script>
</head>
<body>
<p>Click the button to see the result.</p>
<br/>
<br/>
<input type = "button" value = "Result" onclick = "showResult();"/>
</body>
</html>