如果javascript中的语句和范围

时间:2017-02-22 21:44:10

标签: javascript scope

编辑:添加对象

我在函数体内声明的变量存在问题,该函数在从函数返回变量之前似乎消失了:

var customerData = {
  'Joe': {
    visits: 1
  },
  'Carol': {
    visits: 2
  },
  'Howard': {
    visits: 3,
  },
  'Carrie': {
    visits: 4
  }
};

function greetCustomer(firstName) {
  var greeting = '';

  for(var key in customerData){
    if(key === firstName){
      if(customerData[key]['visits'] === 1){
         greeting = "Welcome back, " + firstName + "! We're glad you liked us the first time!";
        console.log(greeting); // here to illustrate issue
      }
      else if(customerData[key]['visits'] > 1){
        greeting = "Welcome back, " + firstName + "! So glad to see you again!";
        console.log(greeting);
      }
    }
    else{
      greeting = "Welcome! Is this your first time?"
    }
  }

  return greeting;
}
greetCustomer("Joe");

输出:

Welcome back, Joe! We're glad you liked us the first time! // here is the correct greeting from the console output
=> 'Welcome! Is this your first time?' // this is what I got
Welcome back, Carol! So glad to see you again! // correct output again
=> 'Welcome! Is this your first time? // base case again.

在整个函数中是否应该greeting可以访问其值以进行分配?我知道我可以回复分支机构的问候语,但我不确定我在这里看到了什么,但我希望有人可以解释。感谢。

2 个答案:

答案 0 :(得分:1)

您的代码会迭代customerData对象中的可用键。当它看到匹配firstName的密钥时,它会分配给greeting并记录它。

然后继续迭代其他键,如果下一个键与firstName不匹配(它可能不会),则greeting被分配{{ 1}}。该值最终从函数返回。当"Welcome! Is this your first time?"恰好是firstName中的最后一个密钥时,您的代码将正常运行,否则将使用默认值重新分配customerData

因此,基本问题是您的代码在找到并处理目标值后继续处理,并重新分配greeting字符串。 greetings变量的范围或可见性没有问题 - 它是一个用于greeting的局部变量。

解决此问题的一种方法是在分配问候语后立即返回(如您所述)。另一种方法是使用greetCustomer退出for循环。然后在函数结束时返回break

greeting

答案 1 :(得分:1)

对于成功条件,立即返回问候语,而不是将其分配给firstname变量。但是对于customerData不是greeting中的关键字之一的条件,只需将"Welcome! Is this your first time?"设置为function greetCustomer(firstName) { var greeting = ''; for(var key in customerData){ if(key === firstName){ if(customerData[key]['visits'] === 1){ return("Welcome back, " + firstName + "! We're glad you liked us the first time!"); console.log(greeting); // here to illustrate issue } else if(customerData[key]['visits'] > 1){ return("Welcome back, " + firstName + "! So glad to see you again!"); } } else{ greeting = "Welcome! Is this your first time?"; } } return greeting; } console.log(greetCustomer("Joe")); &让迭代继续寻找`firstname。

将您的代码更改为[TESTED]:

END_FUNCTION_BLOCK