如何生成字母表数组

How to generate an array of the alphabet?

本文关键字:数组 字母表 何生成      更新时间:2023-09-26

在Ruby中,我可以做('a'..'z').to_a来获得['a', 'b', 'c', 'd', ... 'z']

JavaScript 是否提供了类似的结构?

我个人认为最好的是:

alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');

简洁、有效、易读、简单!

编辑:我已经决定,因为我的答案受到了相当多的关注,以添加选择特定字母范围的功能。

function to_a(c1 = 'a', c2 = 'z') {
    a = 'abcdefghijklmnopqrstuvwxyz'.split('');
    return (a.slice(a.indexOf(c1), a.indexOf(c2) + 1)); 
}
console.log(to_a('b', 'h'));

一个简短的 ES6 版本:

const alphabet = [...'abcdefghijklmnopqrstuvwxyz'];
console.log(alphabet);

如果你非常需要它,你可以很容易地制作一个函数来为你做这件事

function genCharArray(charA, charZ) {
    var a = [], i = charA.charCodeAt(0), j = charZ.charCodeAt(0);
    for (; i <= j; ++i) {
        a.push(String.fromCharCode(i));
    }
    return a;
}
console.log(genCharArray('a', 'z')); // ["a", ..., "z"]

如果有人来这里寻找他们可以硬编码的东西,你可以去:

["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

new Array( 26 ).fill( 1 ).map( ( _, i ) => String.fromCharCode( 65 + i ) );

使用 97 而不是 65 来获取小写字母。

通过使用 ES6 扩展运算符,您可以执行以下操作:

let alphabet = [...Array(26).keys()].map(i => String.fromCharCode(i + 97));

我在上面看到了我喜欢的答案,它是英文字母的硬编码列表,但它只有小写,我也需要大写,所以我决定修改它以防其他人需要它:

const lowerAlph = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

const upperCaseAlp = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

很多这些答案要么使用字符数组,要么使用String.fromCharCode,我提出了一种稍微不同的方法,利用base36中的字母:

[...Array(26)].map((e,i)=>(i+10).toString(36))

这个的优点是纯粹的代码高尔夫,它使用的字符比其他的少。

以防

万一你需要硬编码的字母表array,但打字较少。 上述内容的替代解决方案。

var arr = "abcdefghijklmnopqrstuvwxyz".split("");

将输出这样的数组

/* ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m","n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] */

魔法

[...8337503854730415241050377135811259267835n.toString(36)]

// chrome & firefox
let a1 = [...8337503854730415241050377135811259267835n.toString(36)];
console.log(a1);

// version working on all browsers (without using BigInt)
let a2 = [...[37713647386641440,2196679683172530,53605115].map(x=>x.toString(36)).join``];  
console.log(a2);

尝试

[...Array(26)].map((x,i)=>String.fromCharCode(i + 97))

let alphabet = [...Array(26)].map((x,i)=>String.fromCharCode(i + 97));
console.log(alphabet);

更新

正如您在评论中注意到的那样,这个想法已经用于这个答案(我错过了( - 但这个答案更短,所以把它当作那个旧答案的大小改进

添加到@Sherwin Ablaña Dapito 解决方案(我喜欢在答案中有一些提示(

  • 65 是上字母表的开始,26 是字母表中的字符数
  • fill(( 方法就地将数组中的所有元素更改为静态值 (1(。
  • map(( 应用于每个 elem,创建一个新数组并具有一个 func 作为 arg。
  • =>箭头函数表达式,可以写成function (i){ return i+ 65;}
  • _ 在 map 中:忽略参数(占位符值,此处没有值(并使用 second = index
  • String.fromcharcode是不言自明

new Array( 26 ).fill( 1 ).map( ( _, i ) => String.fromCharCode( 65 + i ) );

使用单行生成字符列表

const charList = (a,z,d=1)=>(a=a.charCodeAt(),z=z.charCodeAt(),[...Array(Math.floor((z-a)/d)+1)].map((_,i)=>String.fromCharCode(a+i*d)));
console.log("from A to G", charList('A', 'G'));
console.log("from A to Z with step/delta of 2", charList('A', 'Z', 2));
console.log("reverse order from Z to P", charList('Z', 'P', -1));
console.log("from 0 to 5", charList('0', '5', 1));
console.log("from 9 to 5", charList('9', '5', -1));
console.log("from 0 to 8 with step 2", charList('0', '8', 2));
console.log("from α to ω", charList('α', 'ω'));
console.log("Hindi characters from क to ह", charList('क', 'ह'));
console.log("Russian characters from А to Я", charList('А', 'Я'));

对于打字稿
const charList = (p: string, q: string, d = 1) => {
  const a = p.charCodeAt(0),
    z = q.charCodeAt(0);
  return [...Array(Math.floor((z - a) / d) + 1)].map((_, i) =>
    String.fromCharCode(a + i * d)
  );
};

只是为了好玩,那么你可以在数组原型上定义一个 getter:

Object.defineProperty(Array.prototype, 'to_a', {
  get: function () {
    const start = this[0].charCodeAt(0);
    const end = this[1].charCodeAt(0);
    return Array.from(Array(end - start + 1).keys()).map(n => String.fromCharCode(start + n));
  }
});

这使得可以执行以下操作:

['a', 'z'].to_a; // [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", ..., "z" ]

这是一个快速的单行

没有依赖关系!

Array.from(Array(26)).map((e, i) => i + 65).map((x) => String.fromCharCode(x));

console.log(Array.from(Array(26)).map((e, i) => i + 65).map((x) => String.fromCharCode(x)));

试试这个

let name = ''
for(let i=0; i<26; i++){
  name+=(i+10).toString(36)
}
console.log(name.split(''))

const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1 }, (_, i) => start + (i * step));
let alpha  = range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map((x) => String.fromCharCode(x));
// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
console.log(alpha);

这是另一种方式:

const chars = [];
for (let i=65; i<=65+25; i++){
  chars.push(String.fromCharCode(i));
}
console.log(chars, Array.isArray((chars )));

使用 JavaScript 的 Array.from 语法,可以创建一个数组并对每个数组元素执行映射函数。创建一个长度为 26 的新数组,并在每个元素上设置等于从当前元素索引的字符代码加上 ascii 幻数获得的值。

const alphabet = Array.from(Array(26), (e, i) => String.fromCharCode(i + 97));

同样,97 可以与 65 互换为大写字母。

数组也可以使用对象的键方法使用值初始化,而不是使用映射的索引

const alphabet = Array.from(Array(26).keys(), i => String.fromCharCode(i + 97));
const ALPHA = Array.from({ length: 26 }, (_, i) => String.fromCharCode('a'.charCodeAt(0) + i)); // ['a', 'b', ...'z']

我相信上面的代码更惯用。足够短,可以成为内联代码。您不必记住起始字母的字符代码,并且可以通过简单地控制长度和开始字母来配置为检索字母表的子集,例如

Array.from({ length: 3 }, (_, i) => String.fromCharCode('x'.charCodeAt(0) + i)) // ['x', 'y', 'z]

//使用地图 1 行代码

let alphabet =[...Array(26)].map( (_,i) => String.fromCharCode(65+i) )

使用数组插入 A-Z

let newArray = []
for(var i = 0; i<26 ; i++){
  newArray.push(String.fromCharCode(65+i))
}

使用数组插入 a-z

let newArray = []
for(var i = 0`enter code here`; i<26 ; i++){
  newArray.push(String.fromCharCode(65+i).toLowerCase())
}
/

/使用拆分

 let a = 'abcdefghijklmnopqrstuvwxyz'.split('');
我喜欢

用这个:

[...Array(26).keys()].map(n => n + 'a'.codePointAt(0)).map(ch => String.fromCharCode(ch))

查看结果

function getAsciiToString(from, total) {
  let count = 0;
  let asciiLetters = "";
  while (count < total) {
    const asciiDigit = from.charCodeAt(0) + count;
    asciiLetters += String.fromCharCode(asciiDigit);
    count++;
  }
  return asciiLetters;
}
console.log(getAsciiToString("a", 26));
console.log(getAsciiToString("A", 26));
console.log(getAsciiToString("0", 10));

这是最有效的,因为没有浪费的临时数组。

const alphabetLowerCase = Array.from({ length: 26 }, (_, i) => String.fromCharCode(97 + i));
console.log(alphabetLowerCase);
const alphabetUpperCase = Array.from({ length: 26 }, (_, i) => String.fromCharCode(65 + i));
console.log(alphabetUpperCase);

我们可以执行以下操作:

var result = ''
for (
    let character = 'a'
    ; character <= 'z'
    ; character = String.fromCharCode(
        character.charCodeAt() + 1
    )
)
    result += character
console.log(result)

在这里result已经是一个类似数组的对象,但是如果您需要它作为实际数组,则可以执行以下操作:

var result = []
for (
    let character = 'a'
    ; character <= 'z'
    ; character = String.fromCharCode(
        character.charCodeAt() + 1
    )
)
    result.push(character)
console.log(result)

var arr = ["C", "D", "X", "A", "B",

"Z"]; console.log(arr.sort( function (a, b( { return a.localeCompare(b( }((;//['A

', 'B', 'C', 'D', 'X', 'Z']

没有Javascript或Jquery不提供类似的东西。您必须创建自己的数组。

您可以尝试如下:

var alpha = ["a","b","c",....];

或者最好像这样尝试:

var index = 97;
$("#parent .number").each(function(i) {
    $(this).html(String.fromCharCode(index++));
});

演示