1、js对象根据键名的ASCII码进行排序,返回排序后的新对象
用法如下:
let data = {"username": "admin", "password": "123456"};
let str = sort_ascii(data);
console.log(str);//打印结果:{ "password": "123456","username": "admin"}
let str = sort_ascii(data);
console.log(str);//打印结果:{ "password": "123456","username": "admin"}
2、js对象根据键名的ASCII码进行排序,并且按照URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串
function sort_ascii(obj) {
let arr = new Array();
let num = 0;
for (let i in obj) {
arr[num] = i;
num++;
}
let sortArr = arr.sort();
let str = '';
for (let i in sortArr) {
str += sortArr[i] + '=' + obj[sortArr[i]] + '&';
}
//去除两侧字符串
let char = '&'
str = str.replace(new RegExp('^\' + char + '+|\' + char + '+$', 'g'), '');
return str;
}
let arr = new Array();
let num = 0;
for (let i in obj) {
arr[num] = i;
num++;
}
let sortArr = arr.sort();
let str = '';
for (let i in sortArr) {
str += sortArr[i] + '=' + obj[sortArr[i]] + '&';
}
//去除两侧字符串
let char = '&'
str = str.replace(new RegExp('^\' + char + '+|\' + char + '+$', 'g'), '');
return str;
}
用法如下:
let data = {"username": "admin", "password": "123456"};
let str = sort_ascii(data);
console.log(str);//打印结果:username=admin&password=123456
let str = sort_ascii(data);
console.log(str);//打印结果:username=admin&password=123456