判断一个字符串,A-Z对应输出0-25,a-z对应输出26-51,有什么简洁的写法吗?

比如:'AZaz' => '0 25 26 51'

我目前的做法:

function Words(words){
    let strArray = []
    for (let s of words){
        if(/[A-Z]/.test(s)) strArray.push(s.charCodeAt(0)-65)
        else if(/[a-z]/.test(s)) strArray.push(s.charCodeAt(0)-71)
    }
    return(strArray.join(' ')) 
}

Words('AZaz')
阅读 8.1k
9 个回答
var Words=(s,a='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')=>s.split('').map(v=>a.indexOf(v)).join('');

Words('AZaz');    

直接写个map,对应存起来

const words = ((chars) => {
    // 生成 map,只会生成一次
    const map = Object.fromEntries(
        [...chars.toUpperCase() + chars].map((char, i) => [char, i])
    );
    
    return function (words) {
        return [...words].map(ch => map[ch]).join(" ");
    };
})("abcdefghijklmnopqrstuvwxyz");

console.log(words("AZaz"));

如果要性能的话 可能更好的选择是 @丶瑶
我也提出我的一种解法。

const dict = {}
for (let i = 0; i < 26; i++) {
  // 65 => 'A'
  dict[String.fromCharCode(65 + i)] = i
  // 97 => 'a'
  dict[String.fromCharCode(97 + i)] = 26 + i
}
'AZaz'.split('').map(v => dict[v]).join(' ')

image.png

function Words(words) {
    let str =  words.split("").reduce((a, b) => 
     a += 
        ((/[A-Z]/.test(b) ? 
        (b.charCodeAt() -65) : 
        b.charCodeAt()-71)
        + " ")
    , "")
    return str.slice(0,str.length-1)
}
function index(ch){
    const charCode = ch.charCodeAt(0);
    const index = charCode & 0b11111;
    const isLower = (charCode & 0b100000) !== 0;
    return index + (isLower ? 25 : -1);
}
console.log(index('A')); // 0
console.log(index('Z')); // 25
console.log(index('a')); // 26
console.log(index('z')); // 51

image.png

Words = s => {
  let m = new Map(Object.entries('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz').map(([a,b])=>[b,a]))
  return s.split('').map(c => m.get(c)).join(' ')
}
新手上路,请多包涵

function Words(words) {
let str = "";

for (let i in words) {

if (words[i].charCodeAt() < 97) {
  str += ` ${words[i].charCodeAt() - 65}`;
}
if (words[i].charCodeAt() >= 97) {
  str += ` ${words[i].charCodeAt() - 71}`;
}

}

return str;
}

Words("AZaz");

字典表,如:
{
'a': 1
}

推荐问题
宣传栏