0

この関数を使用して、同じ長さの 2 つの配列の結果を結合します

例:2つの配列を組み合わせている場合Array AArray B

出力は次の形式になりますarray[Value of Array A]=value of Array B

combined = fields.reduce(function(obj, val, i) {
    obj[val] = edit_opt[i];
    return obj;
}, {});

この関数は、chrome と firefox でテストしたときに必要な機能を実行しますが、IE 8,9 でコードをテストするとエラーが発生します。以下にメッセージを掲載しました。

Web ページのエラーの詳細

> User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2;
> Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR
> 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729) Timestamp: Sat, 21 Jul 2012 10:29:23 UTC


Message: Object doesn't support this property or method
Line: 94
Char: 5
Code: 0
URI: http://x.x.x.x/grid_test/

note: line 94 is the beginning of my combine function.

このエラーを解決するには?

4

1 に答える 1

1

Array.prototype.reduceはECMAScript5の追加です。そのため、標準の他の実装には存在しない場合があります。

これを回避するには、スクリプトの先頭に次のコードを挿入して、ネイティブでサポートされていない実装でreduceを使用できるようにします。

if (!Array.prototype.reduce) {  
        Array.prototype.reduce = function reduce(accumulator){  
        if (this===null || this===undefined) throw new TypeError("Object is null or undefined");  
        var i = 0, l = this.length >> 0, curr;  

        if(typeof accumulator !== "function") // ES5 : "If IsCallable(callbackfn) is false, throw a TypeError exception."  
          throw new TypeError("First argument is not callable");  

        if(arguments.length < 2) {  
          if (l === 0) throw new TypeError("Array length is 0 and no second argument");  
          curr = this[0];  
          i = 1; // start accumulating at the second element  
        }  
        else  
          curr = arguments[1];  

        while (i < l) {  
          if(i in this) curr = accumulator.call(undefined, curr, this[i], i, this);  
          ++i;  
        }  

        return curr;  
      };    
 }  

ソース

于 2012-07-21T10:56:33.103 に答える