基於演算法加密字串 JavaScript


問題

我們要求編寫一個 JavaScript 函式,該函式接收一個字串,並基於以下演算法對其進行加密 −

  • 此字串只包含以空格分隔的單詞。

  • 我們需要使用以下規則加密字串中的每個單詞 −

    • 第一個字母需要轉換為 ASCII 碼。

    • 第二個字母需要與最後一個字母對調。

因此,根據這一規則,字串“good“將被加密成“103doo”。

示例

以下是程式碼 −

 即時演示

const str = 'good';
const encyptString = (str = '') => {
   const [first, second] = str.split('');
   const last = str[str.length - 1];
   let res = '';
   res += first.charCodeAt(0);
   res += last;
   for(let i = 2; i < str.length - 1; i++){
      const el = str[i];
      res += el;
   };
   res += second;
   return res;
};
console.log(encyptString(str));

輸出

103doo

更新於: 20-Apr-2021

644 瀏覽

開啟你的職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.