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

如何使用JS输出从字母A到用户输入字符为止的大小写字母?

从A到用户输入字符的大小写字母输出实现方案

你当前的代码仅能输出对应ASCII区间的单组字符,且存在不必要的eval调用,可按如下逻辑修改实现需求:

优化后完整代码

// 定义起始字符为大写A
const startChar = 'A'
// 获取用户输入并统一转大写,确定终止字符
const endChar = window.prompt('请输入终止字符').toUpperCase()
// 获取起止字符的ASCII编码
const startCode = startChar.charCodeAt(0)
const endCode = endChar.charCodeAt(0)
// 循环遍历编码区间
for (let code = startCode; code <= endCode; code++) {
  // 同时输出当前编码对应的大写、小写字母
  const upper = String.fromCharCode(code)
  const lower = String.fromCharCode(code + 32)
  console.log(`${upper} ${lower}`)
}

实现说明

  • 首先将用户输入统一转大写,避免用户输入小写字符导致区间计算异常
  • 大写字母和对应小写字母的ASCII编码差值为32,不需要额外循环两次即可同时获取大小写字符
  • 移除了不必要的eval调用,直接调用String.fromCharCode传入编码即可生成对应字符
  • 如果需要先连续输出所有大写字母、再连续输出所有小写字母,可调整为两次循环,示例如下:
const startChar = 'A'
const endChar = window.prompt('请输入终止字符').toUpperCase()
const startCode = startChar.charCodeAt(0)
const endCode = endChar.charCodeAt(0)
// 先输出所有大写字母
for (let code = startCode; code <= endCode; code++) {
  console.log(String.fromCharCode(code))
}
// 再输出所有小写字母
for (let code = startCode; code <= endCode; code++) {
  console.log(String.fromCharCode(code + 32))
}

内容的提问来源于stack exchange,提问作者talent in making

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:36:05