angular - 对于角度 4 中大于 10 的值,过滤器 orderby 无法按预期工作
问题描述
import {Pipe, PipeTransform} from 'angular2/core';
@Pipe({ name: 'orderBy' })
export class OrderrByPipe implements PipeTransform {
transform(records: Array<any>, args?: any): any {
return records.sort(function(a, b){
if(a[args.property] < b[args.property]){
return -1 * args.direction;
}
else if( a[args.property] > b[args.property]){
return 1 * args.direction;
}
else{
return 0;
}
});
};
}
请检查一下,它对我有用,但我看到一件事,整数排序假设如果我们取 1,2,3,4,5,6,7,8,9,10,11,12,13。它的行为很奇怪
解决方案
对数组排序时面临的一般问题是由于数组中使用的数据类型。
举个例子 -
console.log(2 > 11) //result is false
console.log("2" > "11") //result is true
这就是为什么您的管道对于 1 到 9 的数字工作正常而在 9 之后失败的原因。
因此,在处理数组元素的比较时应考虑被比较项的数据类型。
编辑 - 排序
考虑以下示例,其中字符串和数字类型比较分别处理。
function orderByComparator(a, b) {
if ((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))) {
//Isn't a number so lowercase the string to properly compare
if (a.toLowerCase() < b.toLowerCase())
return -1;
if (a.toLowerCase() > b.toLowerCase())
return 1;
}
else {
//Parse strings as numbers to compare properly
if (parseFloat(a) < parseFloat(b))
return -1;
if (parseFloat(a) > parseFloat(b))
return 1;
}
return 0; //equal each other
}
console.log("number comparison - ", orderByComparator(2, 11));
console.log("string comparison - ", orderByComparator("2", "11"));
例子
这个 plunkr详细解释了比较(检查 orderBy.ts 管道定义)
我希望这有帮助 :)
推荐阅读
- pypi - 是否可以用我自己的包替换具有特定名称的现有 pip 包?
- syntax - 如何使用 Hugo 嵌套短代码?省略了原始 HTML
- java - 如何使用 redisson 并保持微服务架构紧凑
- ios - 透明导航栏 iOS 13
- sql - 如何在 CASE 语句计算中对重复行求和
- angular - 如何使用 angular-google-charts 制作圆角条
- javascript - 我需要添加什么以及将 JWT 令牌发送到浏览器标头的位置?
- php - PHP拆分和排序新数组中的数据
- python - 余弦相似度为 -1 或 1,但我需要将它们赌为 0 和 1
- selenium - 在 Selenium 中实现数组元素