首页 > 解决方案 > 在javascript中使用箭头函数返回名字和姓氏的首字母

问题描述

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

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

标签: javascript

解决方案


您必须return在大括号内指定。您可以使用charAt()以下方式获取首字母:

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

或:您不需要returnif 删除大括号:

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


推荐阅读