我有一个数组:
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}]
我想使用此代码按类型对汽车对象进行排序
function myFunction() {
cars.sort(function(a, b){
var x = a.type.toLowerCase();
var y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});
displayCars(); // a function to output the result
}
此函数中的 x和y是saab,bww或volvo。如何比较(saab 如果条件语句比较两个字符串而不是比较数字怎么办?为什么它必须返回-1、1和零?
答案 0 :(得分:0)
您是在问为什么这样做吗?
如果是这样,它会起作用,因为JavaScript对lexicographical order有一定的了解。 B在S之前,S在V之前,依此类推。
-1表示变量a应该比变量b低一个索引。
1表示变量a应该比变量b高一个索引。
0表示变量a不应移动。