Interrupting prototype function propagation
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开发者_Python百科)
{
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
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 custom forEach
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 return 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;
}
}
}
};
your code:
function str_search(element, index, array){
if (element.Contains(obj.id) ) {
stored_id = obj.id;
return false;
}
}
listdatatypes.while( str_search );
The following hack would technically work:
var arr = [1, 2, 3, 4];
try {
arr.forEach(function (i) {
if (i > 2) throw 0;
}
} catch (e) {
if (e !== 0) throw e;
}
精彩评论