字符串数组转化数字数组
let values = ['0', '1', '5', '10', '15', '2'];
let valueArr = values.map((item) => {
return Number(item);
});
console.log(valueArr); //[0, 1, 5, 10, 15]
数字数组转化为字符串数组
let strArr = valueArr.map((item) => {
return String(item);
});
console.log(strArr); //["0", "1", "5", "10", "15"]
sort实现排序(无须将字符串数组转化为数字数字也可实现正常排序)
let values = ['0', '1', '5', '2', '10', '15'];
let values2 = [0, 1, 5, 2, 10, 15];
function compare(value1, value2) {
return value1 - value2;
}
//正序排序
values.sort(compare);
console.log(values); // ["0", "1", "2", "5", "10", "15"]
values2.sort(compare);
console.log(values2); // [0, 1, 2, 5, 10, 15]
// 逆序排序
function reverseCompare(value1, value2) {
return value2 - value1;
}
values.sort(reverseCompare);
console.log(values); //["15", "10", "5", "2", "1", "0"]
values2.sort(reverseCompare);
console.log(values2); // [15, 10, 5, 2, 1, 0]