为什么基于字符串索引的数组出现在 angularjs ng-repeat 中排序

Why does a string index based array appear sorted in angularjs ng-repeat

我创建了以下内容:

interface IMap {
[name: string]: string;
}

var map: IMap = {};
map["S"] = "s";
map["C"] = "c";
map["D"] = "d";

当我以角度检查 ng-repeat 时,它按 c、d、s 的顺序打印它们,而不是 s、c、d。为什么要排序?

Objects 未在 JavaScript 中排序。如果你想要订单,你需要使用一个 array.

我不知道如何使用 TypeScript 做到这一点,但我想是这样的:

var map: IMap = [];

Angular 默认按字母顺序对 object literal 进行排序,因为它没有顺序。

将对象字面量想象成一本字典。

angular 将检查您想要迭代的集合类型,下面是源代码的片段,您可以看到 collectionKeys.sort() 按字母数字 ASC 排序。 https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js#L333

if (isArrayLike(collection)) {
  collectionKeys = collection;
  trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
} else {
  trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  // if object, extract keys, sort them and use to determine order of iteration over obj props
  collectionKeys = [];
  for (var itemKey in collection) {
    if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') {
      collectionKeys.push(itemKey);
    }
  }
  collectionKeys.sort();
}

如果你希望它按你放置的顺序排列但仍然使用对象,你可以创建另一个数组来保留键和 ng-repeat 。下面的伪代码

scope.map = {S: 's', C: 'c', D: 'd'};
scope.mapKey = ['S', 'C', 'D'];

<div ng-repeat="key in mapKey">
    {{map[key]}}
</div>