【问题标题】:Interrupting prototype function propagation中断原型函数传播
【发布时间】:2011-07-02 23:19:03
【问题描述】:

在每个表单域上触发事件,我使用原型函数启动一个数据控件。如果它在一个数组内容listdatatypes中找到当前对象id obj.id的字段类型,那么它会进一步处理一些正则表达式控件(当然,还有一个php 覆盖层,但没有 Ajax,因为我想避免重新编码所有内容)。

这就像一个魅力,但我想知道一旦找到针头,如何中断数组针头搜索的传播(例如所谓的 prototype 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) ;


// ...

谢谢

【问题讨论】:

    标签: javascript execution interrupt prototype-programming


    【解决方案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 );
    

    【讨论】:

    • @hometbzz:我想你会选择传统的循环。无需求助于try/catch hack。这是一个while 函数。只需return false; 即可打破循环。
    • 谢谢,这是一个更好的建议;我不这么认为,看着我的鼻子时总是一样的:-)
    【解决方案2】:

    以下 hack 在技术上可行:

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

    【讨论】:

      猜你喜欢
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-15
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 2021-06-16
      相关资源
      最近更新 更多