1

我的 JS 对象定义如下 -

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

在我的应用程序中的某个时刻,我Items从 chrome.storage 获得了这些 () 的列表,我希望能够根据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但没有任何反应......谢谢~

4

2 回答 2

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)复制数组,即获取另一个包含与您的数组相同元素的数组。

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参数是可选的。

于 2013-09-03T16:51:08.807 回答
0

@Oriol:

我刚刚做了一个相同的小提琴http://jsfiddle.net/JaU4g/,但对我来说它确实有效!

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"
于 2013-09-03T16:58:44.853 回答