【发布时间】:2021-03-19 21:27:11
【问题描述】:
我正在尝试按 id 对数组进行排序。但是,当我使用 sort() 方法时,什么也没有发生。
products.sort(function (a, b) {
return a.id - b.id;
});
我该如何解决这个问题?
我的尝试:
constructor(private pokemonService: PokemonService, private typeColorFactory: TypeColorFactoryService, private screenOrientation: ScreenOrientation) {
this.pokemonService.getPokemons(1).subscribe(
res => {
console.log(res);
this.pokemons = res;
this.pokemons.sort((a, b): Pokemon => {
if (a.id < b.id) return -1;
if (a.id > b.id) return 1;
return 0;
});
console.log(this.pokemons);
},
err => {
console.log('HTTP Error', err);
}
);
}
数组始终保持不变!我不知道这是否重要,但是当我在排序中console.log() 时,它不会记录任何内容(但不知道这是否可能)。
型号:
pastebin.com/FLTiZPSA
数据:
更新:
const products=[
{'id':'1','name':'A'},
{'id':'3','name':'C'},
{'id':'4','name':'D'},
{'id':'2','name':'B'},
];
products.sort((a,b)=> {
console.log("test");
return a.id-b.id;
});
this.pokemons.sort((a,b) => {
console.log("test");
return a.id-b.id;
});
products.sort() 记录“测试”。
this.pokemons.sort() 不记录“测试”。
this.pokemonService 的链接:https://pastebin.com/raWJ9isP
【问题讨论】:
-
不,没有帮助:(我已经更新了帖子。
-
你能显示你的数据吗?
-
您的 TypeScript 格式不正确;应该是
sort((a: Pokemon, b: Pokemon) => { -
我试过 sort((a: Pokemon, b: Pokemon) => { ,不幸的是它没有任何区别。
-
您确定您的口袋妖怪具有
id属性并且拼写正确吗?
标签: angular typescript ionic-framework