更新时间:2023-12-06 15:53:34
您必须传递一个将字符串转换为数字的比较器函数:
You'll have to pass in a comparator function that converts the strings to numbers:
allsortedvalues = allsortedvalues.sort(function(a,b) {
return (+a) - (+b);
});
如果您的某些数组条目可能不是格式正确的数字,那么您的比较器将不得不变得更加复杂.
If there's a chance that some of your array entries aren't nicely-formatted numbers, then your comparator would have to get more complicated.
构造(+a)
涉及一元+
运算符,如果a
已经是数字,则该运算符不执行任何操作.但是,如果a
不是 一个数字,则+a
的结果将是解释为 时的a
值,或者是NaN
.通过将字符串检查并解析为数字的字符串表示形式,可以很明显地将字符串解释为.布尔值将转换为false -> 0
和true -> 1
.值null
变为0
,undefined
为NaN
.最后,对象引用通过调用其valueOf()
函数解释为数字,否则调用NaN
.
The construction (+a)
involves the unary +
operator, which doesn't do anything if a
is already a number. However if a
is not a number, the result of +a
will be either the value of a
when interpreted as a number, or else NaN
. A string is interpreted as a number in the obvious way, by being examined and parsed as a string representation of a number. A boolean value would be converted as false -> 0
and true -> 1
. The value null
becomes 0
, and undefined
is NaN
. Finally, an object reference is interpreted as a number via a call to its valueOf()
function, or else NaN
if that doesn't help.
如果愿意,等同于使用Number(a)
中的Number构造函数.它的作用与+a
完全相同.我是个懒惰的打字员.
It's equivalent to use the Number constructor, as in Number(a)
, if you like. It does exactly the same thing as +a
. I'm a lazy typist.