【发布时间】:2017-05-02 20:06:58
【问题描述】:
我有一个 javascript 循环,它遍历数据库中的一些注释并将它们连接成一个字符串以附加到 DOM。它使用noteType 作为键,因此我可以在多个选项卡上分隔不同类型的笔记。
问题是,我需要显示按日期排序的所有注释的组合视图。所以在循环结束时,我将注释附加到一个单独的变量,我称之为 combinedOutput 就目前而言,注释是每个笔记类型的正确日期顺序。但是,当需要将它们全部组合为一个时,两组正确排序的数组将按各自的顺序附加,并在最终输出中丢弃日期顺序。
这是我的代码示例:
// Define our vars
var output = [],
combinedOutput = [],
noteType = '',
noteDate = new Date;
$(data).find('notes>data').each(function() {
var $p = $(this);
noteType = $p.find('noteType').text(),
noteDate = moment.utc($p.find('timestampOrig').text()).toDate()
if (typeof(output[noteType]) == 'undefined') {
output[noteType] = "";
}
if (typeof(combinedOutput[noteDate]) == 'undefined') {
combinedOutput[noteDate] = new Date;
}
// Create our note
output[noteType] += '<div id="message_' + $p.find('recordID').text() + '" class="panel panel-default custom-panel item">';
output[noteType] += 'Something Here';
output[noteType] += '</div>';
// Append to our final output variable
combinedOutput[noteDate] += output[noteType];
});
日期示例
**Note Type: Public**
April 1, 2017
March 5, 2017
April 8, 2017
**Note Type: Private**
April 2, 2017
March 9, 2017
March 11, 2017
**Combined Notes:**
April 1, 2017
March 5, 2017
April 8, 2017
April 2, 2017
March 9, 2017
March 11, 2017
我的最终目标是按其键对combinedOutput 进行排序,该键恰好是一个日期对象。
【问题讨论】:
-
javascript 中的对象永远不能保证被排序。如果顺序很重要,则应使用数组
标签: javascript arrays sorting