var fruits = [{ name: "Banana" }, { name: "Apple" }, { name: "Mango" }, { name: "Orange" }];
var fruits1 = [{ name: 10 }, { name: 26 }, { name: 1 }, { name: 3 }];
var fruits2 = [{ name: '10' }, { name: '26' }, { name: '1' }, { name: '3' }];
// fruits.sort();
function compare(key, order) {
return function (value1, value2) {
var val1 = value1[key];
var val2 = value2[key];
switch (order) {
// 升序
case 'ascending':
if (typeof val1 === 'number') {
return val1 - val2;
} else if (typeof val1 === 'string') {
return val1.localeCompare(val2);
}
break
// 降序
case 'descending':
if (typeof val1 === 'number') {
return val2 - val1;
} else if (typeof val1 === 'string') {
return val2.localeCompare(val1);
}
break
default:
break
}
}
}
fruits.sort(compare('name', 'ascending'))
fruits1.sort(compare('name', 'ascending'))
fruits2.sort(compare('name', 'ascending'))
console.log('---fruits1', fruits1)
console