Skip to content

第 48 期(数据结构-数组):获取字母表 #51

@wingmeng

Description

@wingmeng

题目:

编写一个名为 getAlphabet 的函数,返回一个由 a 到 z 26个字母组成的数组。


参考答案:

思路:利用 ASCⅡ 表中字母编码是连续的这个特点,获得字母 a 的编码作为起始位置,然后累加编号,从而得到字母表。

// 方法1
function getAlphabet() {
  return [...Array(26).keys()].map((_, idx) => String.fromCharCode(97 + idx));
}

// 方法2
function getAlphabet() {
  return new Array(26).fill().map((_, idx) => String.fromCharCode(97 + idx));
}

// 方法3
function getAlphabet() {
  return Array.from({length: 26)).map((_, idx) => String.fromCharCode(97 + idx));
}

// 方法4
function getAlphabet() {
  var len = 26;
  var result = [];

  while(len) {
    result.push(String.fromCharCode(97 + (26 - len)));
    len--;
  }

  return result;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions