在帖子中顯示點贊者,該陣列使用 JavaScript 指定了對某個特定帖子點讚的人員的姓名


問題

我們需要編寫一個 JavaScript 函式,函式中包含一個名稱陣列 (string)。此陣列指定某個社交網站上對特定帖子點贊人員的姓名。

如果點贊數小於或等於三,我們的函式只需返回所有名稱,表明這些人員對帖子點贊。但如果點贊數大於三,我們的函式應返回前兩個名稱和剩餘的計數。

示例

以下為程式碼 −

 活動演示

const names = ['Ram', 'Manohar', 'Jay', 'Kumar', 'Vishal'];
const displayLikes = (names) => {
   return [
      'no one likes this',
      `${names[0]} likes this`,
      `${names[0]} and ${names[1]} like this`,
      `${names[0]}, ${names[1]} and ${names[2]} like this`,
      `${names[0]}, ${names[1]} and ${names.length - 2} others like this`,
   ][
      Math.min(4, names.length)
   ];
};
console.log(displayLikes(names));

輸出

Ram, Manohar and 3 others like this

更新於: 17-Apr-2021

237 次瀏覽

開啟你的 職業生涯

完成課程獲取證書

開始吧
廣告
© . All rights reserved.