最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using a Date as the hash table key - Stack Overflow

programmeradmin0浏览0评论

How can I create a hash table object in JavaSript and use a date as the key? So far I've got this:

var eventHash = {};
for (var i = 0, l = events.length; i < l; i += 1) {
    eventHash[events[i].date.getTime()] = events[i];
}

And then when I want to find the event associated with today I would use this:

var event = eventHash[(new Date(2011, 04, 26, 0, 0, 0, 0)).getTime()];

Can anyone see any pitfalls with this solution, or have any suggestions for improvement?

How can I create a hash table object in JavaSript and use a date as the key? So far I've got this:

var eventHash = {};
for (var i = 0, l = events.length; i < l; i += 1) {
    eventHash[events[i].date.getTime()] = events[i];
}

And then when I want to find the event associated with today I would use this:

var event = eventHash[(new Date(2011, 04, 26, 0, 0, 0, 0)).getTime()];

Can anyone see any pitfalls with this solution, or have any suggestions for improvement?

Share Improve this question asked May 24, 2011 at 2:08 Matty FMatty F 3,7834 gold badges33 silver badges48 bronze badges 6
  • 1 Pitfalls? How sure are you that there'll only ever be one event per day? – nnnnnn Commented May 24, 2011 at 2:14
  • Pitfalls? How can you be sure that the event happened exactly at midnight? – Nick ODell Commented May 24, 2011 at 2:16
  • re those 2 pitfalls: I'm working with dates only (so h, m, s & ms are always 0'd out) and with events that occur daily at most. – Matty F Commented May 24, 2011 at 2:27
  • So no two events can happen on the same day? Even if your requirement allows you to use dates as keys, I imagine in the long run it will be safer to use something else. (Although, I do admit, I have no idea what you are trying to do and keying on dates might just be fine anyway.) – Jeremy Commented May 24, 2011 at 2:43
  • @Jeremy yeah its a finance app and the eventHash I'm building is a list of exceptions to scheduled transactions. there's an eventHash for each schedule, and the transaction can repeat daily at most so is perfectly suitable for what I need it. – Matty F Commented May 24, 2011 at 2:56
 |  Show 1 more ment

3 Answers 3

Reset to default 6

Why wouldn't you just use an ISO8601 representation of the date, so the key would be like 20110426. Creating a date object seems a bit inefficient.

It would also make debugging easier as the property names are more human readable, even if you add hhmmss also.

The only issue I see is that it's pretty limiting if you suddenly need to have multiple events with the same date. Otherwise it should be alright.

Also: Today is May 23, not Apr 26 :)

I have a somewhat similar problem and my solution may help others.

I have a list of "entries", each entry has a timestamp and a value. I want to divide them up into "buckets", one for each day. In Python I would have used collections.defaultdict but since JavaScript does not have something like that I do the following.

If you want to read the keys, remember that when you use a Date as an object key it gets converted as a string.

var get_entries = function() {
    var entries = [];
    entries.push({
        'timestamp': 1381831606,
        'value': 3
    });
    entries.push({
        'timestamp': 1381831406,
        'value': 2
    });
    entries.push({
        'timestamp': 1381531606,
        'value': 6
    });
    entries.push({
        'timestamp': 1381221606,
        'value': 9
    });
    entries.push({
        'timestamp': 1381221601,
        'value': 8
    });
    entries.push({
        'timestamp': 1381221656,
        'value': 7
    });
    return entries;
};

var normalize_date = function(timestamp) {
    // JavaScript timestamps work with milliseconds.
    var dt = new Date(timestamp * 1000);
    return new Date(
        dt.getFullYear(),
        dt.getMonth(),
        dt.getDate()
    );
};

var prepare_data = function() {
    var entry,
        line = {};
    var entries_raw = get_entries();
    for (var i = 0; i < entries_raw.length; i++) {
        entry = entries_raw[i];
        entry.date = normalize_date(entries_raw[i].timestamp);
        // If date not exists in line, create it.
        console.log('Found entry for date', entry.date, 'with value', entry.value);
        if (typeof(line[entry.date]) === 'undefined'){
           line[entry.date] = 0;
        }
        line[entry.date] += entry.value;
    }
    console.log(line);
    return line;
};

prepare_data();

Output:

$ nodejs diaryindex.js
Found entry for date Tue Oct 15 2013 00:00:00 GMT+0200 (CEST) with value 3
Found entry for date Tue Oct 15 2013 00:00:00 GMT+0200 (CEST) with value 2
Found entry for date Sat Oct 12 2013 00:00:00 GMT+0200 (CEST) with value 6
Found entry for date Tue Oct 08 2013 00:00:00 GMT+0200 (CEST) with value 9
Found entry for date Tue Oct 08 2013 00:00:00 GMT+0200 (CEST) with value 8
Found entry for date Tue Oct 08 2013 00:00:00 GMT+0200 (CEST) with value 7
{ 'Tue Oct 15 2013 00:00:00 GMT+0200 (CEST)': 5,
  'Sat Oct 12 2013 00:00:00 GMT+0200 (CEST)': 6,
  'Tue Oct 08 2013 00:00:00 GMT+0200 (CEST)': 24 }
发布评论

评论列表(0)

  1. 暂无评论