原型 - 可列舉 inject() 方法
此方法將根據迭代器的連續結果逐步生成結果值。這可用於陣列構造、數字求和/平均數等。
可選 context 引數是迭代器函式將繫結到的物件。如果使用,迭代器內的 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>
輸出
prototype_enumerating.htm
廣告