如何在JavaScript中从字母字符串获取对应的CharCode编码值?
你当前使用的String.fromCharCode()作用是将字符编码转换为对应字符,刚好是你需求的反向操作。你原有代码里已经通过oneArray[0]取到了首字符'F',但用错了API导致没有拿到编码值,要从字符获取对应的CharCode编码,应该使用字符串实例的charCodeAt()方法。
修正后可直接运行的代码
function solution(someword) { // 可以不用split转数组,字符串本身直接调用charCodeAt即可 let onekey = someword.charCodeAt(0) console.log(onekey) } solution("FROG"); // 控制台输出70
补充说明
如果需要获取整个字符串所有字符的编码,也可以搭配遍历实现,示例如下:
function getAllCharCodes(str) { const codes = [] for(let i = 0; i < str.length; i++) { codes.push(str.charCodeAt(i)) } return codes } getAllCharCodes("FROG") // 返回 [70, 82, 79, 71]
内容的提问来源于stack exchange,提问作者jgrewal
相关产品推荐
相关产品推荐

