gpt4 book ai didi

javascript - javascript 中的 if 语句和作用域

转载 作者:行者123 更新时间:2023-12-01 03:58:35 26 4
gpt4 key购买 nike

编辑:添加对象

我遇到了一个问题,在函数体内声明的变量在从函数返回变量之前似乎就消失了:

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变量。但对于 firstname 不是 customerData 中的键之一的情况,只需将 greeting 设置为 “欢迎!这是您第一次吗?” ?" & 让迭代继续寻找 `firstname.

将您的代码更改为此[已测试]:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com