繁体   English   中英

有没有更好的方法来编写这个JavaScript?

[英]Is there a better way to write this javascript?

有没有更好的方法来编写这个JavaScript?

switch (l) {
    //A
    case '1-1-1':
    case '1-1-2':
    case '1-2-1':
    case '2-1-1':
    case '3-1-1':
        obj.result = 'A';
        break;
    //B
    case '1-2-2':
    case '1-2-3':
    case '2-2-2':
    case '2-2-3':
    case '3-2-2':
    case '3-3-1':
        obj.result = 'B';
        break;
    //C
    case '1-3-2':
    case '1-3-3':
    case '2-3-2':
    case '3-2-3':
        obj.result = 'C';
        break;
    //D
    case '3-3-2':
    case '3-3-3':
        obj.result = 'D';
        break;
    default:
        obj.result = 'AA';
        break;
}

如果您告诉我们您是如何获得这些值的,我们可能会提出一个更简洁的解决方案,但这里是您使用查找表(生成的向后)的方式:

var byResult={
    A: ['1-1-1', '1-1-2', /* ... */],
    B: ['1-2-2', '1-2-3', /* ... */],
    /* ... */
};
var byInput={};
for(var output in byResult) {
    if(!Object.prototype.hasOwnProperty.call(byResult, output)) {
        continue;
    }
    var inputs=byResult[output];
    for(var i=0, l=inputs.length; i<l; i++) {
        var input=inputs[i];
        byInput[input]=output;
    }
}
function lookup(value) {
    if(Object.prototype.hasOwnProperty.call(byInput, value)) {
        return byInput[value];
    }else{
        return 'AA';
    }
}

Thilo在评论中提到的查找表:

var lookup =
{
    '1-1-1': 'A',
    '1-1-2': 'A',
    '1-2-1': 'A',
    '2-1-1': 'A',
    '3-1-1': 'A',

    '1-2-2': 'B',
    '1-2-3': 'B',
    '2-2-2': 'B',
    '2-2-3': 'B',
    '3-2-2': 'B',
    '3-3-1': 'B',

    '1-3-2': 'C',
    '1-3-3': 'C',
    '2-3-2': 'C',
    '3-2-3': 'C',
    '3-3-2': 'C',

    '3-3-3': 'D'
};

及其用法:

obj.result = lookup[l] || 'AA';

我不能说这真的比switch版本更好。

将数字封装到函数中的字母处理中,这样您的主代码就不需要知道翻译是如何完成的。 像这样称呼它:

obj.result = getThing(l);

// or, given your comment that l is formed by concatenating three
// values you could do the concatenation in the function
obj.result = getThing(v1, v2, v3);

然后在getThing()您可以使用现有的switch语句,或Matt Ball的答案中的查找表,或者您喜欢的任何其他方法。 并且您可以随时更改方法,而不会影响调用该函数的代码。

function getThing(v1, v2, v3) {
   var l = v1 + "-" + v2 + "-" + v3;
   // use lookup, switch, whatever
   return "somecode";
}

注意:实际上不要将您的函数称为“getThing”; 将“Thing”替换为描述这些字母代码实际上是什么的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM