You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 06:36:03