1

下面是一个从循环中的数组中提取月份的函数。当找到一个月时,该月在对象 CRIMES_PER_MONTH 中迭代 1。

这可行,但它是一个非常丑陋的解决方案,并且 switch 语句变得很长。那么,我可以使用什么来代替 switch 语句呢?

var crimes_per_month = {
          january: 0,
          february: 0,
          mars: 0,
          april: 0,
          may: 0,
          june: 0,
          july: 0,
          august: 0,
          september: 0,
          oktober: 0,
          november: 0,
          december: 0
};

function AddToMonths(month) {

    switch(month) {

        case 1:
            jan += 1;
        break;

        case 2:
            feb += 1;
        break;

        case 3:
            mar += 1;
        break;

        case 4:
            apr += 1;
        break;

        ... and so on...

    }
}

for(var i = 0; i < incidents.length; i++) {
    month = incidents[i].substring(5, 7);
    AddToMonths(parseInt(month));
}

我想最好的办法是直接在循环中访问对象:

for(var i = 0; i < incidents.length; i++) {
    month = incidents[i].substring(5, 7);
    crimes_per_month[month] += 1;
}

...但这仅适用于数组,我真的想将其保留为对象。

4

5 回答 5

4

最简单的方法是创建crimes_per_month一个数组,以便可以使用addToMonths给定的键直接处理其属性:

crimes_per_month = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
function addToMonths(month) {
    crimes_per_month[month-1] += 1;
}

如果您不希望这样,则需要进行索引到月份名称的转换功能。

var crimes_per_month = {
    january: 0,
    february: 0,
    mars: 0,
    april: 0,
    may: 0,
    june: 0,
    july: 0,
    august: 0,
    september: 0,
    oktober: 0,
    november: 0,
    december: 0
};

function addToMonths(month) {
    var names = ["january", "february", "mars", "april", "may", "june", "july", "august", "september", "oktober", "november", "december"];
    var name = names[month-1];
    crimes_per_month[name] += 1;
}
于 2013-02-18T09:34:08.200 回答
2

您可以简单地使用数组。

var crime_per_month = new Array(13);
for(var i = 1; i <= 12; i++) crime_per_month[i] = 0;
function AddToMonths(month) {
    crime_per_month[month]++;
}
于 2013-02-18T09:32:47.787 回答
2

如果您想保持当前CRIMES_PER_MONTH结构,可以使用带键的数组将月份编号转换为键名:

var addToMonths = (function () {
    var names = ["january", "february", "mars", "april", "may", "june", "july", "august", "september", "oktober", "november", "december"];
    return function (month) {
        CRIMES_PER_MONTH[names[month - 1]]++;
    };
}());
于 2013-02-18T09:39:34.180 回答
0

只需有一组月份名称,您可以查找它们。

var months = ["january", "february", ...],
    month = incidents[i].substring(...),

    incident_month = months[month-1]; // case 1: === "january"

 crimes_per_month[incident_month] += 1; // case 1: === crimes_per_month.january += 1
于 2013-02-18T09:46:14.997 回答
0

我在这里明显错过了什么吗?

它是 JavaScript,所以(几乎)一切都是允许的;)

为什么不直接访问对象成员?您将需要相同的成员名称,crimes_per_month并且incidents_month应该能够执行以下操作:

var crimes_per_month = {january: 0,...};
var incidents_month = {january: 14,....};

function addToMonth(/* string */ monthName) {
  crimes_per_month[monthName] = crimes_per_month[monthName] + 1;
}
于 2013-02-18T10:00:04.010 回答