有人可以帮我写这段代码吗,我正在尝试编写一个函数,该函数从对象中获取名称并返回名称标签: “嗨!我是 [name],来自 [country]。”
我试过这个代码
const GUEST_LIST = {
Randy: "Germany",
Karla: "France",
Wendy: "Japan",
Norman: "England",
Sam: "Argentina"
}
function greeting(name) {
var x = Object.keys(GUEST_LIST);
const array = Object.keys(GUEST_LIST)
.map(function(key) {
return GUEST_LIST[key];
});
var txt ="";
for (let i in x)
{
if (name === x[i])
{
txt = "Hi I'm "+x[i] +", and I'm from " +array[i];
}
else
{
txt = "Hi! I'm a guest";
}
}
return txt;
}
console.log(greeting("Randy"))
但它总是返回“嗨!我是客人”,除非我输入Sam,
答案 0 :(得分:4)
您的问题是,即使您从数组中找到与传递给函数的名称相匹配的名称,您的 for 循环仍将继续循环遍历 ERR_CONNECTION_REFUSED
数组中的其他名称。这意味着在 for 循环的进一步迭代中,您的 x
代码块将运行并覆盖先前设置的 else
值。这就是“Sam”起作用的原因,因为它是 txt
数组中的姓氏,因此 x
不会被 for 循环的进一步迭代覆盖。
关于您的代码的另一件事要注意,for...in
loop shouldn't be used to iterate over an array。它可能会导致访问不需要的值,因为它不仅会遍历数组的索引,还会遍历其他属性。
话虽如此,您正在过度设计您的代码。目前,您的对象存储键值对。名称是键,值是国家/地区。对于对象中的每个键,您可以使用 bracket-notation:
访问它txt
考虑到这个想法,您的 console.log(GUEST_LIST["Randy"]); // Germany
变量可以用作对象的键,然后可以使用它来获取国家/地区。如果 GUEST_LIST 对象不包含您的密钥(即:尝试从您的数组访问它返回的值是 name
/falsy),那么您可以返回默认的“嗨!我是客人”文本:
undefined
答案 1 :(得分:1)
既然没有规范,为什么要一个for
循环,为什么不简单一点呢?
const GUEST_LIST = {
Randy: 'Germany',
Karla: 'France',
Wendy: 'Japan',
Norman: 'England',
Sam: 'Argentina'
}
function greeting (name) {
if (GUEST_LIST[name]) {
return "Hi I'm " + name + ", and I'm from " + GUEST_LIST[name]
} else {
return "Hi! I'm a guest"
}
}
console.log(greeting('Randy'))
console.log(greeting('The guy from the bus stop'))
答案 2 :(得分:0)
理解我的意思是你的代码的工作版本。
for (let i in x)
{
if (name === x[i])
{
txt = "Hi I'm "+x[i] +", and I'm from " +array[i];
break; // <---- stop the loop here when you find a match
}
else
{
txt = "Hi! I'm a guest";
}
}
return txt;
}
答案 3 :(得分:0)
简单易读且简短:
const GUEST_LIST = {
Randy: "Germany",
Karla: "France",
Wendy: "Japan",
Norman: "England",
Sam: "Argentina"
}
function greeting(name){
return (GUEST_LIST[name]) ?
`Hi, I'm ${name} and I'm from ${GUEST_LIST[name]}` :
`Hi! I'm a guest`
}
console.log(greeting("Randy"))