如何使用JavaScript生成包含从A到Z的所有字母的数组?

8 min read

可以使用如下代码实现:

function generateAlphabets() {
  const alphabets = [];
  for (let i = 97; i <= 122; i++) {
    alphabets.push(String.fromCharCode(i));
  }
  return alphabets;
}
// 调用该方法
const result = generateAlphabets();
console.log(result); // [a, b, c, d, ..., x, y, z]

该方法使用 for 循环遍历 97 到 122 之间的 ASCII 码,然后将每一个字符推入一个数组中,最后返回该数组。