是否可以简化这个javascript?

问题描述 投票:0回答:2

我是 javascript 新手,很抱歉我不太了解。我有以下内容,我想让它变得更简单。任何建议将不胜感激。

if (entity == "house") {
    primaryKey = store.getItem('accountID') + "02" + "00";
    table = "Content";
}
if (entity == "street") {
    primaryKey = store.getItem('accountID') + "0000";
    table = "Content";
}
if (entity == "city") {
    var primaryKey = store.getItem('categoryID');
    table = "Reference";
}
if (entity == "location") {
    primaryKey = "0001" + store.getItem('examID');
    table = "Content";
}
javascript
2个回答
7
投票

您可以使用表驱动的方法来完成它,并且没有重复的代码(DRY),如下所示:

var lookupInfo = {
    house: {id: "accountID", prefix, "", suffix: "0200", table: "Content"},
    street: {id: "accountID", prefix: "", suffix: "0000", table: "Content"},
    city: {id: "categoryID", prefix: "", suffix: "", table: "Reference"},
    location: {id: "examID", prefix: "0001", suffix: "", table: "Content"}
};

var primaryKey, data = lookupInfo[entity];
if (data) {
    primaryKey = data.prefix + store.getItem(data.id) + data.suffix;
    table = data.table;
}

除了最小化代码并且不重复任何代码之外,还可以轻松地向表中添加更多选项,而无需编写任何额外的代码。


或者,数据表可以变得更紧凑一点,尽管不太优雅(从纯编程的角度来看,因为硬编码常量):

var lookupInfo = {
    house: ["accountID", "", "0200", "Content"],
    street: ["accountID", "", "0000", "Content"],
    city: ["categoryID", "", "", "Reference"],
    location: ["examID", "0001", "", "Content"]
};

var primaryKey, data = lookupInfo[entity];
if (data) {
    primaryKey = data[1] + store.getItem(data[0]) + data[2];
    table = data[3];
}

无论哪种方式,您都会想到使用实体的查找表,然后使用表驱动的方法来处理每个实体的不同值。


3
投票

您可以使用 switch 语句。 https://developer.mozilla.org/en/JavaScript/Reference/Statements/switch

var primaryKey;
var table = "Content";
switch (entity) {
    case "house":
        primaryKey = store.getItem('accountID') + "0200";
        break;
    case "street":
        primaryKey = store.getItem('accountID') + "0000";
        break;
    case "city":
        primaryKey = store.getItem('categoryID');
        table = "Reference";
        break;
    case "location":
        primaryKey = "0001" + store.getItem('examID');
        break;
    default:
        // do nothing
}

这仍然很冗长,但更容易阅读。

© www.soinside.com 2019 - 2024. All rights reserved.