【问题标题】:Using arrow function in javascript to return the initials of the First Name and Last Name在javascript中使用箭头函数返回名字和姓氏的首字母
【发布时间】:2020-06-08 18:28:43
【问题描述】:

在 javascript 中使用箭头函数时,尝试让控制台日志显示名字和姓氏的首字母。

const getInitials = (firstName, lastName) => {
  firstName + lastName;
}
console.log(getInitials("Charlie", "Brown"));

【问题讨论】:

标签: javascript


【解决方案1】:

您必须在大括号内指定return。您可以使用charAt() 来获取姓名缩写:

const getInitials = (firstName,lastName) => { return firstName.charAt(0) + lastName.charAt(0); }
console.log(getInitials("Charlie", "Brown"));

或者:如果去掉大括号,则不需要return

const getInitials = (firstName,lastName) => firstName.charAt(0) + lastName.charAt(0);
console.log(getInitials("Charlie", "Brown"));

【讨论】:

  • (他们也在寻找首字母而不是整个字符串)
【解决方案2】:

从名称中获取第一个字符。

const getInitials = (firstName, lastName) => `${firstName[0]}${lastName[0]}`
console.log(getInitials("Charlie", "Brown"));

【讨论】:

    【解决方案3】:

    您返回的不是首字母缩写,而是全名。使用[0] 获取字符串的第一个字符。

    在箭头函数中,如果您只想将其作为结果返回,请不要将表达式放在{} 中。

    const getInitials = (firstName, lastName) => firstName[0] + lastName[0];
    console.log(getInitials("Charlie", "Brown"));

    【讨论】:

      【解决方案4】:

      当你给箭头函数一个代码块({})时,你需要显式定义return语句。在您的示例中,您不需要代码块,因为您只想返回一个值。因此,您可以删除代码块,并将返回值放在箭头=> 的右侧。

      为了获取字符串中的第一个字符,您可以使用括号表示法 ([0]) 来索引字符串,.charAt(0),甚至是 destructuring,如下所示:

      const getInitials = ([f],[s]) => f + s;
      console.log(getInitials("Charlie", "Brown"));

      【讨论】:

        【解决方案5】:
        const getInitials = (firstName,lastName) => { return firstName.charAt(0) + lastName.charAt(0); }
        console.log(getInitials("Charlie", "Brown"));
        

        【讨论】:

        • 虽然这个答案可能会解决问题,但请添加一些额外的解释性文字以帮助读者了解它在做什么。
        猜你喜欢
        • 1970-01-01
        • 2012-04-02
        • 1970-01-01
        • 2013-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-12
        相关资源
        最近更新 更多