在JavaScript中将字符转换为ASCII

2ledvvac  于 2023-05-27  发布在  Java
关注(0)|答案(4)|浏览(129)

我首先接受一个字符串输入,并将其更改为拆分数组,但随后我需要将该拆分数组更改为ASCII以进行计算。我该怎么做?

u1ehiz5o

u1ehiz5o1#

字符串输入在技术上已经是一个字符数组。
您可以执行以下操作

asciiKeys = [];
for (var i = 0; i < string.length; i ++)
  asciiKeys.push(string[i].charCodeAt(0));
uubf1zoe

uubf1zoe2#

像这样?

var str= document.URL;
var ascii= str.split('').map(function(itm){
    return itm.charCodeAt(0);
});
var str2=ascii.map(function(itm, i){
    return '#'+i+'=0x'+itm.toString(16)+' ('+String.fromCharCode(itm)+')';
}).join('\n');

alert('original string='+ str+'\nascii codes:\n'+str2);

/*  returned value:
original string=http://localhost/webworks/ghost.html
ascii codes:
#0=0x68 (h)
#1=0x74 (t)
#2=0x74 (t)
#3=0x70 (p)
#4=0x3a (:)
#5=0x2f (/)
#6=0x2f (/)
#7=0x6c (l)
#8=0x6f (o)
#9=0x63 (c)
#10=0x61 (a)
#11=0x6c (l)
#12=0x68 (h)
#13=0x6f (o)
#14=0x73 (s)
#15=0x74 (t)
#16=0x2f (/)
#17=0x77 (w)
#18=0x65 (e)
#19=0x62 (b)
#20=0x77 (w)
#21=0x6f (o)
#22=0x72 (r)
#23=0x6b (k)
#24=0x73 (s)
#25=0x2f (/)
#26=0x67 (g)
#27=0x68 (h)
#28=0x6f (o)
#29=0x73 (s)
#30=0x74 (t)
#31=0x2e (.)
#32=0x68 (h)
#33=0x74 (t)
#34=0x6d (m)
#35=0x6c (l)
*/
3xiyfsfu

3xiyfsfu3#

let str = 'MyString';

let charCodes = [...str].map(char => char.charCodeAt(0));

console.log(charCodes);
// [77, 121, 83, 116, 114, 105, 110, 103]
b1uwtaje

b1uwtaje4#

这将初始化一个大小与字符串长度匹配的数组,并将每个字符Map到其对应的代码:

let str = 'ABCD1234560';
let arr = Array(str.length).fill().map((_, i) => str.charCodeAt(i));
console.log(arr);

这样做的好处是能够提取字符串的一部分。例如,仅前4个字符:

let str = 'ABCD1234560';
let arr = Array(4).fill().map((_, i) => str.charCodeAt(i));
console.log(arr);

或者直接遍历字符串:

let str = 'ABCD1234560';
let arr = [];
for (let i = 0; i < str.length; i++)
  arr.push(str.charCodeAt(i));
 
console.log(arr);

相关问题