首页 > 解决方案 > 对于角度 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。它的行为很奇怪

标签: angular

解决方案


对数组排序时面临的一般问题是由于数组中使用的数据类型。

举个例子 -

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 管道定义)

我希望这有帮助 :)


推荐阅读