按字段浮点数排序



我在主干中有一个应用程序,我想在浮点数的基础上对集合进行排序,但不是做这样的事情:
- 9.90
- 12.50
- 100.50
- 110.50

排序结果如下:
- 100.50
- 110.50
- 12.50
- 9.90

这是我的模型:

 LanguageModel = Backbone.Model.extend({});

我的收藏:

 LanguageCollection = Backbone.Collection.extend({
            model: LanguageModel,
            sort_key: 'price', // default sort key
            initData: function(data){
                return data;
            },
            comparator: function (item) {
                return item.get(this.sort_key);
            },
            sortByField: function (fieldName) {
                this.sort_key = fieldName;
                this.sort();
            }
        });

我的观点:

var TourView = Backbone.View.extend({ 
        initialize: function(){ 
            this.collection_language = new LanguageCollection(); 
            var self = this;
            var success = function(){
                self.render(); 
            };
            var lang = this.importLanguages();
            $.when( lang).done(success);
        }, 
        importLanguages: function(){
            var languages = this.collection_language.initData(jQuery.parseJSON($('#json-languages').html()));
            this.collection_language.set(languages);
            return true;
        },
        render: function(){
            $.each(this.collection_language.models, function( key, value ) {
                value.attributes.price = parseFloat(value.attributes.price).toFixed(2);
            });
            this.collection_language.sortByField('price');
            console.log(this.collection_language);
        } 
    });
在我看来,我

试图解析集合并将浮动价格转换为订单,但这并不能解决我的问题

$.each(this.collection_language.models, function( key, value ) {
                    value.attributes.price = parseFloat(value.attributes.price).toFixed(2);
                });
                this.collection_language.sortByField('price');

似乎排序逻辑还可以。按其他字段排序是否按预期工作?我只想建议在初始化步骤中转换价格。执行此操作的最佳位置是模型的parse方法:

parse : function (data) {
  data.price = +data.price;
  return data;
}

查找问题,toFixed(2)在订单函数中。

我已经改变了这个:

$.each(this.collection_language.models, function( key, value ) {
     value.attributes.price = parseFloat(value.attributes.price).toFixed(2);
});

对此:

$.each(this.collection_language.models, function( key, value ) {
     value.attributes.price = parseFloat(value.attributes.price);
});

现在工作正常

最新更新