在每个循环中从 javascript 个匿名函数中获取 return
Get return from javascript anonymous funcion in each loop(s)
我以前从来没有用过js,现在遇到了一个问题,接下来我该怎么做?
function test()
{
$(xml).find("strengths").each(function()
{
$(this).each(function()
{
(if some condition)
{
//I want to break out from both each loops at the same time here.
// And from main function too!
}
});
});
}
我知道要停止一个循环我只需要 return false
。但是如果我有一些嵌套怎么办?以及如何从主函数 return?
谢谢大家!
你可以使用一个临时变量,像这样:
function test () {
$(xml).find("strengths").each(function() {
var cancel = false;
$(this).each(function() {
(if some condition) {
cancel = true;
return false;
}
});
if (cancel) {
return false;
}
});
}
您可以使用两个变量:
function test()
{
var toContinue = true,
toReturn;
$(xml).find("strengths").each(function()
{
$(this).each(function()
{
if("some condition")
{
toReturn = {something: "sexy there!"};
return toContinue = false;
}
});
return toContinue;
});
if(toReturn) return toReturn;
//else do stuff;
}
我以前从来没有用过js,现在遇到了一个问题,接下来我该怎么做?
function test()
{
$(xml).find("strengths").each(function()
{
$(this).each(function()
{
(if some condition)
{
//I want to break out from both each loops at the same time here.
// And from main function too!
}
});
});
}
我知道要停止一个循环我只需要 return false
。但是如果我有一些嵌套怎么办?以及如何从主函数 return?
谢谢大家!
你可以使用一个临时变量,像这样:
function test () {
$(xml).find("strengths").each(function() {
var cancel = false;
$(this).each(function() {
(if some condition) {
cancel = true;
return false;
}
});
if (cancel) {
return false;
}
});
}
您可以使用两个变量:
function test()
{
var toContinue = true,
toReturn;
$(xml).find("strengths").each(function()
{
$(this).each(function()
{
if("some condition")
{
toReturn = {something: "sexy there!"};
return toContinue = false;
}
});
return toContinue;
});
if(toReturn) return toReturn;
//else do stuff;
}