基於陣列在 JavaScript 中轉換字串字母
假設我們有一個僅包含小寫英語字母的字串。為此問題,我們將字母的單位轉換定義為將其替換為字母表中緊隨其後的字母(包括環繞,即 'z' 旁邊的字母為 'a');
我們需要編寫一個 JavaScript 函式,它以一個字串 str 作為第一個引數和一個與 str 長度相同的數字陣列 arr 作為第二個引數。我們的函式應該準備一個新字串,其中原始字串的字母已按陣列 arr 中存在的相應單位轉換。
例如 -
如果輸入字串和陣列為 -
const str = 'dab'; const arr = [1, 4, 6];
則輸出應為 -
const output = 'eeh';
示例
程式碼如下 -
const str = 'dab';
const arr = [1, 4, 6];
const shiftString = (str = '', arr = []) => {
const legend = '-abcdefghijklmnopqrstuvwxyz';
let res = '';
for(let i = 0; i < arr.length; i++){
const el = str[i];
const shift = arr[i];
const index = legend.indexOf(el);
let newIndex = index + shift;
newIndex = newIndex <= 26 ? newIndex : newIndex % 26;
res += legend[newIndex];
};
return res;
};
console.log(shiftString(str, arr));輸出
控制檯中輸出為 -
eeh
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP