数组中元素超过10个,出现排序错误?
var arr = [“9”, “8”, “7”, “b”, “6”, “5”, “a”,“4”, “3”, “2”, “1”]
for(var i=0;i<arr.length;i++){
console.log(arr[i]);
};
console.log("---------------");
arr.sort(function so(a, b) {
return a>b;
});
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
};
输出结果:
9
8
7
b
6
5
a
4
3
2
1
---------------
5
1
2
3
4
6
7
8
9
a
b
arr.sort( function (a, b) { return isNaN(a - b) ? (a > b) : (a - b) }) |
这个方法只在我这个示例中有作用,我的元素类型实际为
{
“shopCode”: “017f55d2800348e69374f38571cfe9c0”,
“shopName”: “NEELLY 纳俪”,
}
排序还是错误。
function bubbleSort(a, fn) {
for (var i = a.length - 1; i >= 1; i–)
for (var j = 0; j < i; j++)
if (fn(a[j], a[j + 1]))
swapArray(a, j, j + 1);
return a;
}
function selectionSort(a, fn) {
for (var i = a.length - 1; i >= 1; i–) {
var pos = i;
for (var j = 0; j < i; j++)
if (fn(a[j], a[pos]))
pos = j;
if (i != pos)
swapArray(a, i, pos);
}
return a;
}
function swapArray(a, i1, i2) {
[a[i1], a[i2]] = [a[i2], a[i1]];
}
function isFn(obj) {
return typeof obj === ‘function’;
}
function mysort(arr, fn) {
return selectionSort(arr, isFn(fn) ? fn : (a, b) => a > b);
}
module.exports = mysort;
页面引用
var mysort = require(’…/…/sort.js’)
a= mysort(aa, (x, y) => x.aa> y.aa);
var a= a[0]