本文介绍了TypeScript 对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图找出我在打字稿中遇到的一个非常奇怪的问题.它将内联布尔表达式视为第一个值的类型,而不是完整的表达式.

I've been trying to figure out a very strange issue I ran into with typescript. It was treating an inline Boolean expression as whatever the first value's type was instead of the complete expression.

因此,如果您尝试以下简单操作:

So if you try something simple like the following:

var numericArray:Array<number> = [2,3,4,1,5,8,11];

var sorrtedArray:Array<number> = numericArray.sort((n1,n2)=> n1 > n2);

尝试

您将在 sort 方法中收到错误消息,指出参数与调用目标的任何签名都不匹配,因为您的结果是数字而不是布尔值.我想我遗漏了一些东西,因为我很确定 n1>n2 是一个布尔语句.

You will get an error on your sort method saying the parameters do not match any signature of the call target, because your result is numeric and not Boolean. I guess I'm missing something though cause I'm pretty sure n1>n2 is a Boolean statement.

推荐答案

错误完全正确.

正如它试图告诉你的那样,.sort() 接受一个返回数字而不是布尔值的函数.

As it's trying to tell you, .sort() takes a function that returns number, not boolean.

如果第一项较小,则需要返回负数;如果较大则为正,如果相等则为零.

You need to return negative if the first item is smaller; positive if it it's larger, or zero if they're equal.

这篇关于TypeScript 对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:25