2011-07-02 26 views
1

在每個表單字段上觸發事件,我使用原型函數啓動數據控件。如果它發現當前對象的字段類型爲obj.id其中數組內容爲listdatatypes,那麼它進一步進行到一些正則表達式控件(當然,有一個php覆蓋層,但沒有Ajax,因爲我想以避免重新編碼所有內容)。中斷原型函數傳播

這就像一個魅力,但我想知道如何中斷陣列針搜索的傳播(例如所謂的原型2),一旦發現針。

下面是代碼的原則:

// proto 1 
if (!String.prototype.Contains) { 
    String.prototype.Contains = function(stack) { 
     return this.indexOf(stack) != -1; 
    }; 
} 

// proto 2 
if (!Array.prototype.forEach) { 
    Array.prototype.forEach = function(my_callback) 
    { 
    var len = this.length; 
    if (typeof my_callback != "function") 
     throw new TypeError(); 

    var thisp = arguments[1]; 
    for (var i = 0; i < len; i++) 
    { 
     if (i in this) 
      my_callback.call(thisp, this[i], i, this); 
    } 
    }; 
} 

// ... main code abstract 

      function str_search(element, index, array){ 
     // Store the found item ... and would like to stop the search propagation 
      if (element.Contains(obj.id)) 
       stored_id = obj.id; 
      } 
      listdatatypes.forEach(str_search) ; 


// ... 

THX

回答

1

如果你問如果forEach環可破,答案是否定的。

您可以在通過它的函數中設置一個標誌來禁用代碼的主要部分,但這就是它。循環將一直持續到結束。

如果您想打破循環,請改用傳統的for循環,或者編寫一個自定義的forEach類型的方法,該方法可以根據函數參數的返回值來中斷。


編輯:

這裏有一個while當您返回false打破。

Array.prototype.while = function(my_callback) { 
    var len = this.length; 
    if (typeof my_callback != "function") throw new TypeError(); 

    var thisp = arguments[1]; 
    for (var i = 0; i < len; i++) { 
     if (i in this) { 
      var ret = my_callback.call(thisp, this[i], i, this); 
      if (ret === false) { 
       break; 
      } 
     } 
    } 
}; 

代碼:

function str_search(element, index, array){ 
    if (element.Contains(obj.id)) { 
     stored_id = obj.id; 
     return false; 
    } 
} 
listdatatypes.while(str_search); 
+0

THX,我希望... – hornetbzz

+1

@hometbzz:我覺得你會剛去尋找一個傳統的循環。無需訴諸「try/catch」黑客攻擊。這是'while'功能。只是'返回false;'打破循環。 – user113716

+0

thx,這是一個更好的建議;我沒那麼想,總是和我一樣看着鼻子結束:-) – hornetbzz

1

下破解在技術上的工作:

var arr = [1, 2, 3, 4]; 
try { 
    arr.forEach(function (i) { 
    if (i > 2) throw 0; 
    } 
} catch (e) { 
    if (e !== 0) throw e; 
} 
+0

thx,看起來很不錯,我會嘗試這個方向。 – hornetbzz