当我尝试在for循环中对对象进行排序时,它是按递减顺序流,但是当我尝试在排序后在控制台中打印我的对象时,它再次以升序显示。
function sortObject(object) {
var sortedObj = {},
keys = _.keys(object);
var keysReverse = keys.reverse();
_.each(keysReverse, function(key) {
sortedObj[key] = object[key];
console.log(sortedObj);
});
return sortedObj;
}
var obj5 = {
3: 'some',
7: 'every',
2: 'all'
}
sortObject(obj5);
如何按降序按键对对象进行排序?
答案 0 :(得分:0)
反向数组不会对数组进行排序。
var keysReverse = _.sortBy(keys, function(num){ return num });
function sortObject(obj) {
var sortedObj = {},
keys = _.keys(obj);
var keysReverse = _.sortBy(keys, function(num) {
return num
});
_.each(keysReverse, function(key) {
sortedObj[key] = obj[key];
});
return sortedObj;
}
var obj5 = {
3: 'some',
7: 'every',
2: 'all'
}
console.log(sortObject(obj5));
<script src="
https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>