編輯:添加的對象if語句和範圍在javascript
我在與這似乎消失了從函數返回的變量之前函數體內聲明的變量的問題:
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'變量寫入內容。只返回上一次迭代中設置的值。 – JJJ
該變量在整個函數中都是絕對可見的。您的錯誤在其他地方 – artemisian