[英]Using arrow function in javascript to return the initials of the First Name and Last Name
在 javascript 中使用箭头函数时,试图让控制台日志显示名字和姓氏的首字母。
const getInitials = (firstName, lastName) => { firstName + lastName; } console.log(getInitials("Charlie", "Brown"));
您必须在大括号内指定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"));
你不是在返回首字母,而是在返回全名。 使用[0]
获取字符串的第一个字符。
在箭头函数中,如果您只想将其作为结果返回,请不要将表达式放在{}
。
const getInitials = (firstName, lastName) => firstName[0] + lastName[0]; console.log(getInitials("Charlie", "Brown"));
从名称中获取第一个字符。
const getInitials = (firstName, lastName) => `${firstName[0]}${lastName[0]}` console.log(getInitials("Charlie", "Brown"));
当你给一个箭头函数一个代码块 ( {}
) 时,你需要明确定义return
语句。 在您的示例中,您不需要代码块,因为您只想返回一个值。 因此,您可以删除代码块,而是将返回值放在箭头=>
的右侧。
为了获得字符串中的第一个字符,您可以使用括号表示法 ( [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.