js中Array.sort()对纯数字排序错误

在js中对纯数字的的数组用sort()函数排序时,会发现的他的排序是错误的,这是因为它采用的unicode编码导致的

arr=[2,6,3,4,11,1];
arr.sort();
console.log(arr);

返回结果:[1, 11, 2, 3, 4, 6]

解决方法:

arr.sort(function (a,b) {
return a-b;
});
console.log(arr);

返回结果:[1, 2, 3, 4, 6, 11]

 

posted @ 2017-12-17 22:08  发奋图强的小菜  阅读(1880)  评论(0编辑  收藏  举报