编辑:添加对象
我在函数体内声明的变量存在问题,该函数在从函数返回变量之前似乎消失了:
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
可以访问其值和以进行分配?我知道我可以回复分支机构的问候语,但我不确定我在这里看到了什么,但我希望有人可以解释。感谢。
答案 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