中断原型函数传播
在每个表单字段上触发事件,我使用原型函数启动数据控件。如果它在数组内容listdatatypes中找到当前对象idobj.id的字段类型,那么它会进一步处理一些正则表达式控件(当然,有一个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
Firing events on every form field, I start a data control using prototype functions. If it finds the type of field of the current object id obj.id among an array contents listdatatypes, then it proceeds further to some regex controls (of course, there is a php overlayer but no Ajax as I'd like to avoid recoding everything).
This works like a charm, but I'm wondering how to interrupt the propagation of the array needle search (eg the so called prototype 2) once the needle has been found.
Here is the code principle :
// 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您询问是否可以打破
forEach
循环,答案是否定的。您可以在传递给它的函数中设置一个标志来禁用代码的主要部分,但仅此而已。循环将持续到结束。
如果您想中断循环,请改用传统的
for
循环,或者编写自定义的forEach
类型的方法,该方法可以根据函数参数的返回值进行中断。编辑:
这是一个
while
,当您返回false
时,它会中断。您的代码:
If you're asking if a
forEach
loop can be broken, the answer is no.You could set a flag in the function you pass it to disable the main part of the code, but that's about it. The loop will continue until the end.
If you want to break the loop, use a traditional
for
loop instead, or write a customforEach
type of method that can be broken based on the return value of your function argument.EDIT:
Here's a
while
that breaks when you returnfalse
.your code:
从技术上讲,以下 hack 是可行的:
The following hack would technically work: