编写一个函数repeatAlpha,它接受一个字符串并显示它
重复每个字母字符的次数与其字母索引相同。
const range = (start, stop, step) => Array.from( { length: Math.ceil((stop - start) / step) }, (_, i) => start + i * step ); const upperAlpha = range("A".charCodeAt(0), "Z".charCodeAt(0) + 1, 1).map((x) => String.fromCharCode(x) ); const lowerAlpha = range("a".charCodeAt(0), "z".charCodeAt(0) + 1, 1).map((x) => String.fromCharCode(x) ); function getAlphaIndex(char) { if (char === char.toUpperCase()) { return upperAlpha.indexOf(char) + 1; } if (char === char.toLowerCase()) { return lowerAlpha.indexOf(char) + 1; } } function repeatAlpha(text) { let occurrence = []; Array.from(text).forEach((char) => { let count = getAlphaIndex(char); let result = Array(count).fill(char).join(""); occurrence.push(result); }); return occurrence.join(""); } console.log(repeatAlpha("Becky")); console.log(repeatAlpha("neNgi")); console.log(repeatAlpha("ChInwendu")); console.log(repeatAlpha("dindustack"));
BBeeeeeccckkkkkkkkkkkyyyyyyyyyyyyyyyyyyyyyyyyy nnnnnnnnnnnnnneeeeeNNNNNNNNNNNNNNgggggggiiiiiiiii CCChhhhhhhhIIIIIIIIInnnnnnnnnnnnnnwwwwwwwwwwwwwwwwwwwwwwweeeeennnnnnnnnnnnnndddduuuuuuuuuuuuuuuuuuuuu ddddiiiiiiiiinnnnnnnnnnnnnndddduuuuuuuuuuuuuuuuuuuuusssssssssssssssssssttttttttttttttttttttaccckkkkkkkkkkk
以上是根据字母顺序索引重复字符串中的字符的详细内容。更多信息请关注PHP中文网其他相关文章!