简体   繁体   English

typescript排序错误

[英]typescript sort is wrong

I have array:我有数组:

let a = [{id: "-1", name: "a"}, { id: "0", name: "b" }, { id: "1", name: "c" }]

I do the following:我执行以下操作:

a = a.sort(x => <number>x.id);

But for some reasons I have item with id = "0" in the last position. What's the reason of it and how can I fix it?但由于某些原因,我在最后一个 position 中有id = "0"的项目。这是什么原因,我该如何解决?

Also I tried to change id = "0" -> id = "-2" in array but now if I sort again I see the following order: -1, -2, 1 .我还尝试更改数组中的id = "0" -> id = "-2"但现在如果我再次排序,我会看到以下顺序: -1, -2, 1 What's wrong?怎么了?

Maybe there is an error in casting one type to another?也许将一种类型转换为另一种类型时出错? I mean string to number我的意思是stringnumber

Typescript is not a runtime language, it compiles to JS. Typescript 不是运行时语言,它编译成 JS。 Doing a TS cast will only instruct the TS compiler to treat x.id aa number it will not perform a runtime cast.进行 TS 转换只会指示 TS 编译器将 x.id 视为一个number ,而不会执行运行时转换。

What you want is to do a JS cast to number, eg Number(x.id)您想要的是将 JS 强制转换为数字,例如Number(x.id)

Also, to properly sort you'll need to compare two items:此外,要正确排序,您需要比较两个项目:

a.sort((x, y) => Number(x.id) - Number(y.id))

Try this.试试这个。

a.sort((a, b) => { if (a.id < b.id) return -1; else if (a.id > b.id) return 1; else return 0; });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM