如何使用JavaScript将字符转换为ASCII码?

例如:

从“\n”中得到10。


当前回答

对于那些想要获取字符串中所有ASCII码的平均值的人:

const ASCIIAverage = (str) =>Math.floor(str.split("))。map(item => item. charcodeat (0)).reduce((prev,next) => prev+next)/str.length) console.log (ASCIIAverage(“Hello World !”)

其他回答

将字符串转换为UTF-8的数组(流):

const str_to_arr_of_UTF8 = new TextEncoder().encode("Adfgdfs");
// [65, 100, 102, 103, 100, 102, 115]

注意:ASCII是UTF-8的一个子集,所以这是一个通用的解决方案

您可以输入一个字符并使用此代码获取Ascii码

例如输入字符a 你得到Ascii码65

函数myFunction () { var str = . getelementbyid (id1); If (str.value=="") { str.focus (); 返回; } var a="ASCII码== > "; . getelementbyid(“演示”)。innerHTML = a + str.value.charCodeAt (0); } <p>检查ASCII码</p> < p > 输入任意字符: <input type="text" id="id1" name="text1" maxLength="1"> </br> < / p > <按钮onclick = " myFunction ()>获取ASCII码</按钮> < span style=" font - family:宋体;" > < / p >

将字符串转换为累积数:

const stringToSum = str => [...str||”A“].reduce((a, x) => and += x.codePointAt(0), 0); console.log(stringToSum(“A”)); 65 console.log(stringToSum(“Roko”)); 411 console.log(stringToSum(“Stack Overflow”));1386

用例:

假设你想根据用户名生成不同的背景颜色:

const stringToSum = str => [...str||"A"].reduce((a, x) => a += x.codePointAt(0), 0); const UI_userIcon = user => { const hue = (stringToSum(user.name) - 65) % 360; // "A" = hue: 0 console.log(`Hue: ${hue}`); return `<div class="UserIcon" style="background:hsl(${hue}, 80%, 60%)" title="${user.name}"> <span class="UserIcon-letter">${user.name[0].toUpperCase()}</span> </div>`; }; [ {name:"A"}, {name:"Amanda"}, {name:"amanda"}, {name:"Anna"}, ].forEach(user => { document.body.insertAdjacentHTML("beforeend", UI_userIcon(user)); }); .UserIcon { width: 4em; height: 4em; border-radius: 4em; display: inline-flex; justify-content: center; align-items: center; } .UserIcon-letter { font: 700 2em/0 sans-serif; color: #fff; }

对于那些想要获得字符串的所有ASCII码的和的人:

'Foobar'
  .split('')
  .map(char => char.charCodeAt(0))
  .reduce((current, previous) => previous + current)

或者,ES6:

[...'Foobar']
  .map(char => char.charCodeAt(0))
  .reduce((current, previous) => previous + current)

为了支持来自ES6的所有UTF-16(也非bmp /补充字符),string.codePointAt()方法可用;

此方法是charCodeAt的改进版本,它只支持< 65536(216 -单个16位)的unicode码点。