var customerData = {
'Joe': {visits: 1},
'Carol': {visits: 2},
'Howard': {visits: 3},
'Carrie': {visits: 4}
};
function greetCustomer(firstName) {
var greeting = '';
var token = customerData[firstName];
var value = token['visits'];
if (firstName in customerData === false) {
greeting = 'Welcome! Is this your first time?';
} else if (value === 1) {
greeting = 'Welcome back, ' + firstName + ', We\'re glad you liked us the first time!';
} else if (value > 1) {
greeting = 'Welcome back, ' + firstName + '! So glad to see you again!'
}
return greeting;
}
console.log(greetCustomer('Nobody'));

此if / else函数中的三个条件。没有通过测试的唯一条件是第一个。真的不知道为什么,因为逻辑看起来合法。我怀疑它与访问嵌套对象位有关,但无法弄清楚如何。
答案 0 :(得分:3)
好像你只需要重新安排你的逻辑。如果对象中不存在该名称,那么您的令牌变量将为null,并且当您尝试引用该null对象的属性时,您的应用程序将中断。在尝试获取您的令牌值后,如果它为null,则欢迎新人。如果不为null,则继续为现有人员提供逻辑。
var customerData = {
'Joe': {visits: 1},
'Carol': {visits: 2},
'Howard': {visits: 3},
'Carrie': {visits: 4}
};
function greetCustomer(firstName) {
var token = customerData[firstName];
if (token == null) {
return 'Welcome! Is this your first time?';
} else {
var value = token['visits'];
if (value === 1) {
return 'Welcome back, ' + firstName + ', We\'re glad you liked us the first time!';
} else if (value > 1) {
return 'Welcome back, ' + firstName + '! So glad to see you again!'
}
}
return '';
}
console.log(greetCustomer('Nobody'));