生成26字母的方法总结

在做项目过程中会用到生成26字母(大写)的问题。下面总结两种方法生成26字:

第一种:采用for循环(代码相对多一点):

let alphabets=[]

const start=‘A’.charCodeAt(0);       //可返回指定位置的字符的 Unicode 编码;

const  end=‘Z’.charCodeAt(0);

for(let i=start;i<=end;++i){

alphabets.push(String.fromCharCode(i));

}

console.log(alphabets)//["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"]

 第二种:采用ES6中Array.from()方法,Array.from()传入一个参数,可以把类似数组的解构转换成数组。传两个参数类似于数组的map()方法,用来对每个元素进行处理,将处理后的值放入返回的数组。

Array.from(arrayLike).map(x => x * x);

Array.from([1, 2, 3], (x) => x * x)

******************************************************************************************

 

const start=‘A’.charCodeAt(0);   

const arr=Array.from(new Array(26),(v,i)=>{

return String.fromCharCode(start+i)

}

 

posted on 2022-11-07 14:45  破晓以后  阅读(207)  评论(0编辑  收藏  举报