繁体   English   中英

if else语句javascript返回false语句

[英]if else statement javascript returns false statement

有人可以帮我写这段代码,我正在尝试编写一个函数,该函数从一个对象中获取一个名称并返回一个名称标签: “嗨!我是 [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

您的问题是,即使您从数组中找到与传递给函数的名称相匹配的名称,您的 for 循环仍将继续循环遍历x数组中的其他名称。 这意味着在 for 循环的进一步迭代中,代码的else块将运行并覆盖先前设置的txt值。 这就是“Sam”起作用的原因,因为它是x数组中的姓氏,因此txt不会被 for 循环的进一步迭代覆盖。

关于您的代码的另一件事要注意, 不应使用for...in循环来迭代 array 它可能会导致访问不需要的值,因为它不仅会遍历数组的索引,还会遍历其他属性。

话虽如此,您正在过度设计您的代码。 目前,您的对象存储键值对。 键是名称,值是国家。 对于对象中的每个键,您可以使用括号表示法访问它:

console.log(GUEST_LIST["Randy"]); // Germany

考虑到这个想法,您的name变量可以用作您的对象的键,然后可以使用它来获取国家/地区。 如果 GUEST_LIST 对象不包含您的密钥(即:尝试从您的对象访问密钥返回的值是假的),那么您可以返回默认的"Hi! I'm a guest"文本:

 const GUEST_LIST = { Randy: "Germany", Karla: "France", Wendy: "Japan", Norman: "England", Sam: "Argentina" }; function greeting(name) { const country = GUEST_LIST[name]; if(country) return "Hi I'm "+name +", and I'm from " +country; else return "Hi! I'm a guest"; } console.log(greeting("Randy"));

既然没有规范,何必有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'))

为了理解我的意思,这里是您代码的工作版本。

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;
}

简单易读且简短:

 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"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM