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

• 55

``````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')``````

9 个回答
✓ 已被采纳
``````var Words=(s,a='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')=>s.split('').map(v=>a.indexOf(v)).join('');

Words('AZaz');    ``````

``````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(' ')``````

``````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``````

``````Words = s => {
let m = new Map(Object.entries('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz').map(([a,b])=>[b,a]))
return s.split('').map(c => m.get(c)).join(' ')
}``````
X
• 4

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
}

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进