Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wingmeng opened this issue Jul 2, 2019 · 0 comments
Open

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

wingmeng opened this issue Jul 2, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Jul 2, 2019

题目:

编写一个名为 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;
}
@wingmeng wingmeng changed the title 第 48 期(ECMAScript-语法):获取字母表 第 48 期(数据结构-数组):获取字母表 Jul 2, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant