javascript排序功能排序错误 [英] javascript sort function sorting wrong
问题描述
您好,我有一个文本框,其值类似于
Hello I have a textbox having values like
<input type="hidden" value="2,1,4,5,3,6,7,8,9,10,11,12" class="sortvalues" id="1_1_parent">
现在我要获取此文本框的值,想要将值拆分为数组,然后最后需要排序的数组.
Now what I want to take the value of this textbox, want to split the values to array and then as last result I need a sorted array.
我做了什么.
allsortedValues = $(".sortvalues").val();
allsortedValues = allsortedValues.split(",");
allsortedValues = allsortedValues.sort();
当我检查数组
console.log(allsortedValues);
它显示
1,10,11,12,2,3,4,5,6,7,8,9
将数组排序为1, 10, 11, 12, 2.....
我什至用过
allsortedValues = allsortedValues.split(",").map(function(x){return parseInt(x)});
在应用排序之前,在其他情况下,我什至使用了parseInt
之类的
before applying sort and in other case I have even used parseInt
like
for(var i = 0; i < allsortedValues.length; i++) {
allsortedValues[i] = parseInt(allsortedValues[i]);
}
在应用排序之前,但在所有情况下结果都是相同的.会有人指导我在做什么错吗?
before applying sort but in all cases result is same. Will some one guide what am I doing wrong?
推荐答案
您必须传递一个将字符串转换为数字的比较器函数:
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.
这篇关于javascript排序功能排序错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!