gpt4 book ai didi

javascript - AngularJS $filter ('orderBy' ) 奇怪的排序

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:02:38 25 4
gpt4 key购买 nike

看起来 AngularJS $filter("orderBy") 的工作方式与 Array.prototype.sort 不同。我为这个问题写了例子:

模板:

<div ng-app="app" ng-controller="ctrl">
<div>arr1 angular </br>{{ arr1ang }}</div>
<div>arr2 angular </br>{{ arr2ang }}</div>
<div>arr1 js </br>{{ arr1js }}</div>
<div>arr2 js </br>{{ arr2js }}</div>
</div>

Controller :

angular.module('app', []);

function ctrl ($scope, $filter) {
arr1 = [
{value: "AA"},
{value: "AB"},
{value: "aa"},
{value: "ab"}
];
arr2 = [
{value: "d"},
{value: "D"},
{value: "w"},
{value: "e"},
{value: "i"},
{value: "O"},
{value: "o"},
{value: "r"}
];

$scope.arr1ang = $filter('orderBy')(arr1, "value");
$scope.arr2ang = $filter('orderBy')(arr2, "value");

function comp(a,b){
if (a.value > b.value)
return 1;
else if (b.value > a.value)
return -1;
else
return 0;
}

arr1.sort(comp);
arr2.sort(comp);
$scope.arr1js = arr1;
$scope.arr2js = arr2;
}

angular
.module('app')
.controller('ctrl', ctrl);

结果:

arr1 angular
[{"value":"AA"},{"value":"aa"},{"value":"AB"},{"value":"ab"}]
arr2 angular
[{"value":"d"},{"value":"D"},{"value":"e"},{"value":"i"},{"value":"O"},{"value":"o"},{"value":"r"},{"value":"w"}]
arr1 js
[{"value":"AA"},{"value":"AB"},{"value":"aa"},{"value":"ab"}]
arr2 js
[{"value":"D"},{"value":"O"},{"value":"d"},{"value":"e"},{"value":"i"},{"value":"o"},{"value":"r"},{"value":"w"}]

我做了一个关于它的 Codepen 示例 here .

我不明白什么,或者这是 AngularJS 中的错误?

最佳答案

Angularjs 按字母顺序排序,不区分大小写。在 JavaScript 中,字符串比较区分大小写。

一种解决方案是在比较之前将所有值转换为小写或大写字符串。

关于javascript - AngularJS $filter ('orderBy' ) 奇怪的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32911139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com