[英]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.