编辑:添加的对象
我在函数体内声明的变量有问题,该变量似乎在从函数返回之前消失了:
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
是否不应该在整个函数中可见以访问其值并进行赋值?我知道我可以从分支机构那里返回问候,但是我不确定在这里看到的内容,但是我希望有人能解释一下。谢谢。 最佳答案
对于成功条件,请立即返回greeting,而不是将其分配给greeting
变量。但是对于firstname
不是customerData
的键之一的情况,只需将greeting
设置为"Welcome! Is this your first time?"
并让迭代继续查找`firstname。
将您的代码更改为此[TESTED]:
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"));
关于javascript - JavaScript中的if语句和范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42402870/