比switch语句更好的解决方案

时间:2013-02-18 09:29:47

标签: javascript loops refactoring switch-statement

下面是一个从循环中的数组中提取月份的函数。当找到一个月时,对象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;
}

...但是这个ony适用于数组,我真的想把它作为一个对象。

5 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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]++;
}

答案 2 :(得分: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]]++;
    };
}());

答案 3 :(得分: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

答案 4 :(得分:0)

我在这里显然想念一些东西吗?

这是JavaScript,所以(几乎)允许一切;)

为什么不直接访问对象成员? 您需要在crimes_per_monthincidents_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;
}