简体   繁体   English

在javascript中使用箭头函数返回名字和姓氏的首字母

[英]Using arrow function in javascript to return the initials of the First Name and Last Name

Trying to have console log show the initials of the first and last name when using arrow functions in javascript.在 javascript 中使用箭头函数时,试图让控制台日志显示名字和姓氏的首字母。

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

You have to specify return inside the curly brackets.您必须在大括号内指定return You can use charAt() to get the initials:您可以使用charAt()来获取首字母:

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

OR: You do not need the return if remove the curly brackets:或者:如果删除大括号,则不需要return

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

You're not returning the initials, you're returning the whole name.你不是在返回首字母,而是在返回全名。 Use [0] to get the first character of a string.使用[0]获取字符串的第一个字符。

In an arrow function, don't put the expression in {} if you just want to return it as a result.在箭头函数中,如果您只想将其作为结果返回,请不要将表达式放在{}

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

Get first chars from names.从名称中获取第一个字符。

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

When you give an arrow function a code block ( {} ), you need to explicitly define the return statement.当你给一个箭头函数一个代码块 ( {} ) 时,你需要明确定义return语句。 In your example, you don't need a code block since you're only wanting to return a single value.在您的示例中,您不需要代码块,因为您只想返回一个值。 So, you can remove the code block, and instead place the return value to the right of the arrow => .因此,您可以删除代码块,而是将返回值放在箭头=>的右侧。

In order to get the first characters in your strings, you can use bracket notation ( [0] ) to index the string, .charAt(0) , or even destructuring like so:为了获得字符串中的第一个字符,您可以使用括号表示法 ( [0] ) 来索引字符串、 .charAt(0) ,甚至可以像这样进行解构

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

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

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

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