2014-01-16 48 views
0

我有以下一段代碼,並且在我將Prototype.js包含到頁面後,這段代碼已經開始崩潰。與原型js的JavaScript衝突

  function JsonArrayByProperty(objArray, prop, direction) { 
      if (arguments.length < 2) throw new Error("sortJsonArrayByProp requires 2 arguments"); 
      var direct = arguments.length > 2 ? arguments[2] : 1; //Default to ascending 

      if (objArray && objArray.constructor === Array) { 
       var propPath = (prop.constructor === Array) ? prop : prop.split("."); 
       objArray.sort(function (a, b) { 
        for (var p in propPath) { 
         if (a[propPath[p]] && b[propPath[p]]) { 
          a = a[propPath[p]]; 
          b = b[propPath[p]]; 
         } 
        } 
        a = a.match(/^\d+$/) ? +a : a; 
        b = b.match(/^\d+$/) ? +b : b; 
        return ((a < b) ? -1 * direct : ((a > b) ? 1 * direct : 0)); 
       }); 
      } 
     } 

它打破了在以下幾行錯誤

Uncaught TypeError: Object #<Object> has no method 'match' 

    a = a.match(/^\d+$/) ? +a : a; 
    b = b.match(/^\d+$/) ? +b : b; 
+0

那麼,顯然'a'和'b'是對象,而不是字符串... – Andy

回答

3

你的問題很可能開始在這條線:

for (var p in propPath) { 

一旦你添加的prototype.js到你的頁面,你不能使用使用for(foo in bar)迭代數組的常見(但不正確)快捷方式。這是因爲數組元素不再是簡單的字符串或浮點數,它們是完整的「擴展」對象,如果對它們進行正確的迭代,它們恰好返回字符串或浮點數。

for(var i = 0; i < propPath.length; i++) { 

將讓你回到正軌。

+0

感謝隊友......原來這是調用函數是JSON.stringfy(xxxx)的年齡問題的罪魁禍首,沒有與原型工作浮出水面,我將不得不改變現有的代碼,你提到的原因。 代碼搞砸了這一行調用函數中的數組 'var finalData = jQuery.parseJSON(JSON.stringify(someData));' –

+0

這裏有一個很棒的頁面:http://api.prototypejs.org/language/Array/ - 閱讀關於不使用for/in來循環訪問數組的章節。如果你重構你的代碼來代替使用'yourArray.each()',你會有更快樂的時光。 – Walter