However, we will find a problem in use. The array sorting method here is not sorted by the number size we imagine, but changes the original data according to the string test results. This is not what we want.
So how can we get what we want to sort according to the number sizes in our minds? We can write a function to implement it ourselves.
The code copy is as follows:
var values = [0, 1, 5, 10, 15];
// asc ascending function
function compareAsc(value1, value2) {
if (value1 > value2) {
return 1;
} else if (value1 < value2) {
return -1;
} else {
return 0;
}
}
// desc descending function
function compareDesc(value1, value2) {
if (value1 > value2) {
return -1;
} else if (value1 < value2) {
return 1;
} else {
return 0;
}
}
values.sort(compareAsc);
console.log(values); // [0, 1, 5, 10, 15]
values.sort(compareDesc);
console.log(values); // [15, 10, 5, 1, 0]