Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

arrays - How can I convert ASCII code to a word using JavaScript for loop

Looking to solve the following code in order to come up with the name for the below array

 let name=[42,67,74,62,6A,1F,58,64,60,66,64,71];
 for(let i=0;i<name.length;i++)
 {
 name[i] =name[i]+1;
 }

Any suggestions what would be the output?

Thanks

question from:https://stackoverflow.com/questions/66052380/how-can-i-convert-ascii-code-to-a-word-using-javascript-for-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your initial array is not a valid array because 6A and 1F are not valid numbers in JavaScript. Furthermore, if all the numbers in the array are hexidecimal numbers, you would need to precede them with 0x for them to behave correctly (because the base10 number 42 is not the same as the base16 number 42). So lets get your array in order first:

let name = [0x42,0x67,0x74,0x62,0x6A,0x1F,0x58,0x64,0x60,0x66,0x64,0x71];

We could have also used strings and parsed them into base16 (hex) numbers:

let name = ['42','67','74','62','6A','1F','58','64','60','66','64','71'].map(n => parseInt(n, 16));

Now we can use String.fromCharCode to determine what the array says:

name.map(String.fromCharCode).join('')

Though I'm not sure what that says or means...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...