---
title: "jQuery模拟prototype的inject方法"
author: "WKsandy"
date: "2010-08-30T23:57:10Z"
tags: []
categories: ["Web前端"]
slug: "jquery-prototype-inject"
draft: false
lastmod: "2011-05-20T14:35:14Z"
id: 751279
url: "https://wksandy.iteye.com/blog/751279"
---

首先来看看prototype.js里的inject方法  
    手册中的描述:

      inject(accumulator, iterator) -&gt; accumulatedValue  基于迭代子所产生的前一个结果递增地构建一个结果值。可以用来构建数组、数字数额／平均值等等。

    用法: 

```
[1, 2, 3].inject([], function(array, value) { 
    array.push(value * value); return array;
}); 
// 构建给定数组各元素平方的数组 -> [1, 4, 9]
```

 

    在jQuery也能找到个方法能达到上面的效果  
    手册中的描述:

      jQuery.map(array,callback) -&gt; Array 将一个数组中的元素转换到另一个数组中。作为参数的转换函数会为每个数组元素调用，而且会给这个转换函数传递一个表示被转换的元素作为参数。转换函数可以返回转换后的值、null（删除数组中的项目）或一个包含值的数组，并扩展至原始数组中。

```
$.map( [1,2,3], function(value){
    return value * value;
}); 
// -> [1, 4, 9]
```

 

    现在我要把一个数组里各个元素值累加,比如\[1,2,3,4]要得到10  
    用prototype的inject方法实现

```
$R(1,4).inject(0, function(acc, value) {
    return acc + value;
}) 
// -> 10
```

 

   这回map方法不好用了，map方法是转换到数组去的，我们直接要值，没关系，还有其他方法

   jQuery.each(obj,callback)  通用例遍方法，可用于例遍对象和数组。

 

```
var result =0; 
$.each( [1,2, 3,4], function(i,value){ 
    result += value; 
}); 
//result->10;
```

 

    当然，prototype也有each的遍历方法,实现方法差不多

 

```
var result =0; 
[1, 2, 3,4].each(function(value,i){ //[1，2，3，4]正好是个范围用$A($R(1,4))或者$R(1, 4)或者$(1,2,3,4)都行 
    //另外prototype和jQuery的回调函数参数顺序是反的 
    result += value; 
}); 
//result->10;
```

 

    现在我在考虑能不能也给jQuery加个inject方法呢

    ok,就模拟prototype,以插件形式来给jQuery对象扩展个inject方法吧

 

```
;(function($) {
        $.extend({
                inject : function(_array, memo, iterator) {
                      $.each(_array, function(index, value) {
                             memo = iterator(memo, value, index);
                       });
                       return memo;
                }
        });
})(jQuery);
```

 

    好了，现在就来看看写的插件能调用到方法的效果吧

 

```
$.inject([1, 2, 3, 4], [], function(array, value) {
       array.push(value * value);
       return array;
}); // -> [1, 4, 9,16]
$.inject([1, 2, 3, 4], 0, function(acc, value) {
       return acc + value;
}); // 返回数组各元素累加后的值 ->10;
$.inject([1, 2, 3, 4, 5], 1, function(acc, value) {
       return acc * value;
});// 返回数组各元素相乘后的值 ->120
```

 

注:在prototype1.6版本新加段iterator = iterator.bind(context);用于动态绑定this上下文

```
//这个我一开始的写法
iterator = (function(fn, context) {
        var args = Array.prototype.slice.call(arguments, 2);
        return args.length == 0 ? function() {
                return fn.apply(context, arguments);
        } : function() {
                return fn.apply(context, args.concat.apply(args, arguments));
        };
})(iterator, context);

//这个是把ptototype中用到相关方法整合的结果
iterator = (function(fn, context) {
        if (arguments.length < 3 && typeof arguments[1] == "undefined")
                return fn;
        var args = Array.prototype.slice.call(arguments, 2);
        return function() {
                var a = (function(array, args) {
                        var arrayLength = array.length, length = args.length;
                        while (length--)
                                array[arrayLength + length] = args[length];
                        return array;
                })(Array.prototype.slice.call(args, 0), arguments);
                return fn.apply(context, a);
        };
})(iterator, context);
```