使用 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

205 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.