我使用下面的帮助程序迭代JSON数组并根据条件返回结果,以查找帐户是否已关闭(OpenOrClosedDesc=='Closed'
)。我收到了所有已关闭的帐户。但是现在我想在没有关闭帐户的情况下在屏幕上打印错误消息。
Handlebars.registerHelper('each_Closed', function(list, opts) {
var i, result = '';
try {
//console.log("List Closed length "+ list.length)
for (i = 0; i < list.length; i++)
if (list[i].OpenOrClosedDesc == 'Closed'){
// console.log("List Closed "+ list[i].OpenOrClosedDesc == 'Closed')
result = result + opts.fn(list[i]);
}
return result;
}catch(e){
}
});
HTML代码:
<div id = "Revolving_ClosedAcc">
{{#repData}}
{{#each_Closed arf.TradeLine.TradeLine.[Revolving Accounts]}}
.
.
.
.
.
{{/each_Closed}}
{{/repData}}
</div>
编辑可能重复的说明: 我试图从else分支返回错误消息,但它没有给出准确的结果。它只是显示如果发现其中一个帐户已关闭,则没有已关闭的帐户。它不会通过for循环。 for循环是主要路径,因为我想迭代整个对象数组。
编辑每个帐户的计数:
Handlebars.registerHelper('each_Closed', function(list, opts) {
var i, result = '',resCounter=0,closedAccountFound = false;
try {
//console.log("List Closed length "+ list.length)
for (i = 0; i < list.length; i++) {
if (list[i].OpenOrClosedDesc == 'Closed') {
// console.log("List Closed "+ list[i].OpenOrClosedDesc == 'Closed')
result = result + opts.fn(list[i]);
resCounter++;
closedAccountFound = true;
}
}
console.log(resCounter);
return closedAccountFound ? result : "No close account found.";
}catch(e){
}
});
我在console.log中得到了数(resCounter) 但是我怎么能回归呢,换句话说我怎么能把它打印在车把里呢? 我必须写另一个帮手吗?
我该怎么做?
提前致谢。
答案 0 :(得分:1)
只需添加变量closedAccountFound = false
并在找到任何已关闭的帐户时将其指定为true,然后在返回结果之前检查值closedAccountFound
是否为真然后返回结果,否则返回消息。
Handlebars.registerHelper('each_Closed', function(list, opts) {
var i, result = '', closedAccountFound = false;
try {
//console.log("List Closed length "+ list.length)
for (i = 0; i < list.length; i++)
if (list[i].OpenOrClosedDesc == 'Closed'){
// console.log("List Closed "+ list[i].OpenOrClosedDesc == 'Closed')
result = result + opts.fn(list[i]);
closedAccountFound = true;
}
return closedAccountFound ? result : "No close account found.";
}catch(e){
}
});