在Angular 6中,如果遇到数组排序错误的问题,可以尝试以下解决方法:
let myArray: number[] = [5, 1, 8, 3, 2];
myArray.sort((a, b) => a - b);
console.log(myArray); // 输出 [1, 2, 3, 5, 8]
let myArray: number[] = [5, 1, 8, 3, 2];
myArray.sort(function(a, b) {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
});
console.log(myArray); // 输出 [1, 2, 3, 5, 8]
npm install lodash
然后,在组件中引入Lodash库:
import * as _ from 'lodash';
接下来,使用Lodash的排序函数进行排序:
let myArray: number[] = [5, 1, 8, 3, 2];
let sortedArray = _.sortBy(myArray);
console.log(sortedArray); // 输出 [1, 2, 3, 5, 8]
以上方法可以帮助您在Angular 6中解决数组排序错误的问题。