【问题标题】:JS - beginner - function isMaleName()JS - 初学者 - 函数 isMaleName()
【发布时间】:2021-08-30 06:47:31
【问题描述】:

在波兰语中,大多数女性名字以字母“a”结尾,这有助于快速识别性别。除了“Bonawentur”是男性名字。

我需要写一个函数来告诉你:

  • 如果男性名字 - 真
  • 如果女性名字 - 错误
  • 如果“博纳文图拉” - 是的

这就是我所做的: 示例 1:

function isMaleName(name) {
  let pieces = name.split("");
  let last = pieces[pieces.length - 1];
  if ((name = "bonawentura")) {
    return true;
  } else if ((last = "a")) {
    return false;
  } else {
    return true;
  }
}

2 个条件完成:

  • 如果男性名字 - 真
  • 如果“博纳文图拉” - 是的

示例 2:

function isMaleName(name) {
  let pieces = name.split("");
  let last = pieces[pieces.length - 1];
  if ((last = "a")) {
    return false;
  } else {
    return true;
  }
}

1 个条件完成:

  • 如果女性名字 - 错误

【问题讨论】:

  • 这些是赋值,不是相等检查
  • 我想这可能是一个学习任务,但return name === 'bonawentura' || 'a' !== name[name.length - 1]; 可以。剖析它,也许会给你新的见解。
  • 是的@Yoshi,你是对的。这是学习任务。
  • @thinkgruen 说您使用的是赋值符号 = 而不是相等检查 ===

标签: javascript function


【解决方案1】:

您正在分配一个值而不是检查它。
你应该使用name == "bonawentura" 而不是name = "bonawentura"

【讨论】:

    【解决方案2】:
    function isMaleName(name) {
        let pieces = name.split("");
        let last = pieces[pieces.length - 1];
        if (name === "bonawentura") {
          return true;
        } else if (last === "a") {
          return false;
        } else {
          return true;
        }
      }
    
    

    我认为应该是这样的,使用两个或三个= 而不是使用一个=

    【讨论】:

    • 谢谢,好的,现在正在工作。但有一件事。 "bonawentura" = false "boNAweNtura" = false 我可以做些什么来改变这一点,每次我写 "Bonawentura" 时它都会显示为真。
    • 只需将if (name === "bonawentura") 更改为if (name.toLowerCase() === "bonawentura"),它应该可以工作
    • 它可以工作,但仍然有很多代码,可以在一行中完成(见我的回答)
    【解决方案3】:

    您可以在一行中完成,并支持小写/大写/boNAweNtura:

    const isMaleName = name => !name.endsWith("a") || name.toLowerCase()==="bonawentura";
    
    console.log(isMaleName("Joe")) // true
    console.log(isMaleName("Lena")) // false
    console.log(isMaleName("boNAweNtura")) // true
    console.log(isMaleName("David")) // true
    console.log(isMaleName("Sara")) // false

    【讨论】:

      【解决方案4】:

      我上面的评论可能有点误导。所以这里是完整的:

      function isMaleName(name) {
        // convert input to lowercase
        name = name.toLowerCase();
      
        // check if it's the fixed string 'bonawentura'
        return name === 'bonawentura'
            // if not, check if it not ends with an 'a'.
            || 'a' !== name[name.length - 1];
      }
      

      参考:

      【讨论】:

        猜你喜欢
        • 2023-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-26
        相关资源
        最近更新 更多