Javascript函数返回undefined for template helper

时间:2014-06-16 18:18:34

标签: javascript jquery

创建模板助手以返回要在DOM中显示的变量,并且我的函数返回undefined,因此不会影响DOM。不完全确定为什么,虽然我觉得它好像是一个具有约束力的问题。这是代码:

supportNumber: function(){
            var jobSupportNumber = state.user.jobs.each(function(job){
                console.log(jobOrder.get("jobId"));
                console.log("test");
                console.log(job.get("id"));
                if(jobOrder.get("jobId") == job.get("id")){
                    var jobNumber = job.get("supportNumber");
                    console.log(jobNumber);
                    return jobNumber;
                } 
                else{
                    console.log("this fired");
                }
            });
            console.log(jobSupportNumber);
            return jobSupportNumber;
}

我的控制台记录很多,以确保返回值,并且一直返回到最终返回语句之前,返回jobSupportNumber为undefined。如果将它返回总是未定义,我做错了什么?

2 个答案:

答案 0 :(得分:1)

.each()不会返回它包装的任何函数的值。内部函数结果仅用于控制.each()循环。

试试这个:

supportNumber: function(){
  var jobSupportNumber = null;

  state.user.jobs.each(function(job){
   if(jobOrder.get("jobId") == job.get("id")){
     jobSupportNumber = job.get("supportNumber");
     return false;  // tell .each() to quit looping
   } 
  });

  return jobSupportNumber;
}

答案 1 :(得分:0)

根据您的代码,state.user.jobs.each() 将返回jobNumber。该返回适用于您的匿名函数。 (你有function(job)

要获得该值,您需要更像这样的东西:

supportNumber: function(){
    var jobSupportNumber;
    state.user.jobs.each(function(job){
    console.log(jobOrder.get("jobId"));
    console.log("test");
    console.log(job.get("id"));
    if(jobOrder.get("jobId") == job.get("id")){
        var jobNumber = job.get("supportNumber");
        console.log(jobNumber);
        /* Set the value and just plain return, instead */
        jobSupportNumber = jobNumber;
        return;
    } 
    else{
        console.log("this fired");
    }
});
console.log(jobSupportNumber);
return jobSupportNumber;
}