JS对象排序日期排序

时间:2013-09-03 16:37:23

标签: javascript jquery

我的JS对象定义如下 -

var item = {};
item[guid()] =
{
    symbol: $('#qteSymb').text(),
    note: $('#newnote').val(),
    date: $.datepicker.formatDate('mm/dd/yy', dt) + " " + dt.getHours() + ":" + minutes,
    pagename: getPageName()
};

在我的应用中的某个时刻,我从chrome.storage获取了一个列表(Items),我希望能够根据date

对其进行排序

这就是我正在做的事情

var sortable = [];

            $.each(Items, function (key, value) {
                if (value.symbol == $('#qteSymb').text() || all) {                        
                    sortable.push([key, value]);
                }
            });

            console.log(sortable);

            sortable.sort(function (a, b) {
                a = new Date(a[1].date);
                b = new Date(b[1].date);
                return a > b ? -1 : a < b ? 1 : 0;
            });

            console.log(sortable);

它似乎不起作用。第一个和第二个console.log(sortable);是相同的。我尝试将return a > b ? -1 : a < b ? 1 : 0;更改为return a < b ? -1 : a > b ? 1 : 0;只是为了看看我是否对sortable进行了任何更改,但没有任何反应...... 谢谢〜

2 个答案:

答案 0 :(得分:1)

两个console.log显示相同的数组,因为当您使用console.log(sortable)时,sortable通过引用传递,并且控制台输出在完成脚本后发生 - 当sortable已经已经排序。

让您的代码变得简单:

var arr = [3,2,1];
console.log(arr); // Produces `[1,2,3]` because its printed
                  // to the console after `arr.sort();`
arr.sort();
console.log(arr); // Produces `[1,2,3]`, as expected

演示http://jsfiddle.net/Rfwph/


解决方法

如果您希望能够在修改之前使用数组console.log进行查看,则可以使用.slice(0) 复制数组,即获取< strong>另一个数组,其中包含与数组相同的元素。

var arr = [3,2,1];
console.log(arr.slice(0)); // [3,2,1]
arr.sort();
console.log(arr); // [1,2,3]

演示http://jsfiddle.net/Rfwph/2/

修改:更好地使用.slice(0)代替.slice(),这在FF上受支持,但ecma262规范说只有end参数是可选的。

答案 1 :(得分:0)

@Oriol:

我只是做了一个相同的小提琴http://jsfiddle.net/JaU4g/,但对我而言,DID有效!

var ar=[3,1,8,4,7,2,4,1]
console.log(ar.join(','));
ar.sort();
console.log(ar.join(','));

,并提供:

[18:55:31.616] "3,1,8,4,7,2,4,1"
[18:55:31.616] "1,1,2,3,4,4,7,8"