一行代码生成26个字母

53 阅读1分钟

使用 String.fromCharCode 即可

map 方式

Array(26).fill().map((_, i) => String.fromCharCode(97 + i))
// ['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']
Array(26).fill().map((_, i) => String.fromCharCode(65 + i))
// ['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']
Array(26).fill().map((_, i) => String.fromCharCode(97 + i)).join('')
// 'abcdefghijklmnopqrstuvwxyz'
Array(26).fill().map((_, i) => String.fromCharCode(65 + i)).join('')
// 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

reduce 方式

Array(26).fill().reduce((p, c, i) => p.concat(String.fromCharCode(97 + i)), [])
// ['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']
Array(26).fill().reduce((p, c, i) => p + String.fromCharCode(97 + i), '')
// 'abcdefghijklmnopqrstuvwxyz'