我正在尝试对数组进行排序:
var mapped = [{
wiFi: true,
megapixel: '20 MP'
},{
wiFi: false,
megapixel: '25 MP'
},{
wiFi: true,
megapixel: '25 MP'
},{
wiFi: true,
megapixel: '21 MP'
}];
我想对这两个属性进行排序(首先是 WiFi)。这是我正在做的事情的一个非常简单的版本,但属性可以由用户决定,所以我有一个看起来有点像这样的函数:
var fields = ['wiFi', 'megapixel'];
// Sort our mapped array
mapped.sort(function (a, b) {
// Loop through our properties
fields.forEach(function (field) {
// Get our value (skip the first)
var x = a[field.name];
var y = b[field.name];
// Switch on the type
switch (typeof x) {
// Boolean
case "boolean":
// Return our value
return x === y ? 0 : x ? -1 : 1;
// Default
default:
// Return our value
return x === y ? 0 : x < y ? -1 : 1;
}
});
});
但我的数组根本没有排序。有谁知道为什么吗?
最佳答案
尝试手动迭代而不是使用内部函数的迭代。
mapped.sort(function(a,b) {
var x, y, i, l = fields.length;
for( i=0; i<l; i++) {
x = a[fields[i]];
y = b[fields[i]];
if( x === y) continue; // proceed to next field to compare
switch(typeof x) {
case "boolean":
return x ? -1 : 1;
// could do other things, eg. case "string": return x.localeCompare(y);
default:
return x < y ? -1 : 1;
}
}
return 0; // all fields compared equal
});
关于JavaScript 排序函数未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36912197/