方向:编写一个名为“greetCustomers”的函数。
根据名称,“greetCustomers”会根据客户访问餐厅的次数返回问候语。请参阅customerData对象。
问候语应该有所不同,具体取决于他们预订的名称。
案例1 - 未知客户(customerData中不存在名称):
var output = greetCustomer('Terrance'); 的console.log(输出); // - > '欢迎!这是你的第一次吗?'
案例2 - 仅访问过一次的客户('访问'值为1):
var output = greetCustomer('Joe'); 的console.log(输出); // - > “欢迎回来,乔!我们很高兴你第一次喜欢我们!'
案例3 - 重复客户:('访问'值大于1):
var output = greetCustomer('Carol'); 的console.log(输出); // - > “欢迎回来,乔!很高兴再次见到你!'
注意: *您的函数不应更改customerData对象以更新访问次数。
var customerData = {
'Joe': {
visits: 1
},
'Carol': {
visits: 2
},
'Howard': {
visits: 3,
},
'Carrie': {
visits: 4
}
};
这是我的代码:
function greetCustomer(firstName){
var greeting = ''
for (var keys in customerData){
for (var k in customerData[keys])
if (customerData[keys][k] < 0 ) greeting = 'Welcome! Is this your first time?'
else if (customerData[keys][k] === 1) greeting = "Welcome back, " + firstName + "! We're glad you liked us the first time!"
else if (customerData[keys][k] >= 2) greeting = "Welcome back, " + firstName + "! So glad to see you again!"
}
return greeting
}
greetCustomer("Carol")
为什么不通过案例一。有没有更好的方法来访问该名称并分配或关联它的访问次数?
答案 0 :(得分:2)
您无需遍历整个对象,只需按名字查找:
var customerData = {
'Joe': {
visits: 1
},
'Carol': {
visits: 2
},
'Howard': {
visits: 3,
},
'Carrie': {
visits: 4
}
};
function greetCustomer(firstName) {
var greeting = '';
if (!customerData[firstName]) {
// if they're not found in data, it's their first time
greeting = 'Welcome! Is this your first time?';
} else if (customerData[firstName].visits === 1) {
greeting = "Welcome back, " + firstName + "! We're glad you liked us the first time!";
} else if (customerData[firstName].visits >= 2) {
greeting = "Welcome back, " + firstName + "! So glad to see you again!";
}
return greeting;
}
// tests
console.log(greetCustomer("Joe"));
console.log(greetCustomer("Carol"));
console.log(greetCustomer("Howard"));
console.log(greetCustomer("Carrie"));
console.log(greetCustomer("Bob"));
答案 1 :(得分:1)
注意:最后else if
可能只是简单else
声明
var customerData = {
'Joe': {
visits: 1
},
'Carol': {
visits: 2
},
'Howard': {
visits: 3
},
'Carrie': {
visits: 4
}
};
function greetCustomer(firstName) {
var greeting = '';
if (!customerData[firstName]){
greeting = 'Welcome! Is this your first time?';
}else if (customerData[firstName].visits === 1){
greeting = "Welcome back, " + firstName + '! ' + "We're glad you liked us the first time!";
}else{
greeting = 'Welcome back, ' + firstName + '! ' + 'So glad to see you again!';
}
return greeting;
}
console.log(greetCustomer('Carrie'));
//Welcome back, Carrie! So glad to see you again!