Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中排序JSON日期?(How do I sort a JSON date in javascript?)

The problem I encounter is that the .sort function doesn't work in my code.

(我遇到的问题是.sort函数在我的代码中不起作用。)

So I am wondering why and I also would like to know the solution.

(所以我想知道为什么,我也想知道解决方案。)

Here is my full code.

(这是我的完整代码。)

So I have a set of json data with username, text message, and a date when the user texted.

(所以我有一组带有用户名,短信和用户发短信日期的json数据。)

I am able to display the data, but now I want to order them by date.

(我可以显示数据,但是现在我想按日期排序。)

/**
 * Call to load the test messages.
 */
function loadTestMessages() {
    var request = new XMLHttpRequest();
    request.open('GET', 'data/testmessages.json', true);

    request.onload = function () {
        if (request.status == 200) {
            var messages = JSON.parse(request.response);
            showAllMessages(messages);
        } else {

            console.error("could not load testmessages.json");
        }
    };

    request.onerror = function () {
        console.error("could not load testmessages.json");
    };

    request.send();
}

/**
 * Make a "block" div
 */
function messageDiv(kindClass, html) {
    return '<div class="' + kindClass + '">' + html + '</div>';
}

/**
 * Display all messages 
 * @param {Array} messages
 */
function showAllMessages(messages) {

    for (i = 0; i < messages.length; i++) {
        var name = messages[i].user_id;
        var content = messages[i].content;
        var date = messages[i].created_at;
        var container = document.getElementById('container');
        //   date.sort(function (a, b) { return a - b });
        //   console.info(date);
        container.innerHTML += messageDiv('block', name + ': </br> ' + content + ' </br> ' + date + ' </br> ');
    }

}

loadTestMessages();
  ask by Icognito translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you want to sort the messages array by the created_at date.

(我认为您想按created_at日期对messages数组进行排序。)

If that is correct, you can do it in one line:

(如果是正确的话,您可以一行完成:)

messages.sort(function (a, b) { return b.created_at - a.created_at; })

This assumes that created_at holds a Date object.

(假设created_at拥有一个Date对象。)

If it is a string instead, then you have to parse it to a Date .

(如果它是字符串,则必须将其解析为Date 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...