2012-07-21 18 views
0

結合我使用此功能長度相等錯誤,而試圖兩個數組中的jQuery

的兩個數組的結果如結合:如果是合併兩個數組說,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測試我的代碼,我得到一個錯誤。 我已在下面發佈消息。

網頁錯誤的詳細信息

> 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. 

如何解決這個問題?

+0

嘗試添加 「無功組合= ...」 的 「組合= ...」 – 2012-07-21 10:53:18

+0

的'reduce'功能也沒有在IE 8。這樣你就可以支持,而不是離開了。 – Amberlamps 2012-07-21 10:54:08

+0

未實施。嘗試在這些瀏覽器中運行'[] .reduce'並查看其差異。 – davin 2012-07-21 10:54:41

回答

1

Array.prototype.reduce是ECMAScript 5的補充;因此它可能不存在於標準的其他實現中。

可以通過在你的腳本的開頭插入下面的代碼,允許使用減少其本身不支持它實現的解決此。

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; 
     };  
} 

source

+0

@工程師爲我工作得很完美,謝謝你,夥伴們,我一整天早上都在嘲笑我,並且感謝你和雷亞斯,戴文和安伯蘭特一起幫忙。 – user1542535 2012-07-21 11:11:01

+0

@ user1542535歡迎來到SO,如果答案適合你,那麼你可以[接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)它。 – Engineer 2012-07-21 11:16:47