fromCharCode() 可接受一个指定的 Unicode 值,然后返回一个字符串。
常用数字、字母对应Unicode 的值
for(var i=48;i<=57;i++){
document.write(String.fromCharCode(i)) //0123456789
}
for(var i=65;i<=90;i++){
document.write(String.fromCharCode(i)) //ABCDEFGHIJKLMNOPQRSTUVWXYZ
}
for(var i=97;i<=122;i++){
document.write(String.fromCharCode(i)) //abcdefghijklmnopqrstuvwxyz
}
用于
用于为接口返回的城市列表排序
接口返回的城市列表数据是这样的
{
"E": [
{
"name": "鄂州",
"id": 184
},
{
"name": "峨眉山",
"id": 213
}
],
"A": [
{
"name": "安庆",
"id": 70
},
{
"name": "鞍山",
"id": 96
}
],
"R": [
{
"name": "日照",
"id": 58
}
],
"M": [
{
"name": "玛沁县",
"id": 2382
},
{
"name": "玛多县",
"id": 2387
}
]
}
用以下方法把数据从A-Z排序
function sortAllCities(allCities){
let newObj = {};
for(let i=65;i<=90;i++){
if(allCities[String.fromCharCode(i)]){
newObj[String.fromCharCode(i)] = allCities[String.fromCharCode(i)];
}
}
return newObj;
}
排序后数据是这样的
{
"A": [
{
"name": "安庆",
"id": 70
},
{
"name": "鞍山",
"id": 96
}
],
"E": [
{
"name": "鄂州",
"id": 184
},
{
"name": "峨眉山",
"id": 213
}
],
"M": [
{
"name": "玛沁县",
"id": 2382
},
{
"name": "玛多县",
"id": 2387
}
],
"R": [
{
"name": "日照",
"id": 58
}
]
}