0

I have an if-statement that looks like this:

if ("Bolagsmän" in nicerows){
        var contact = this.makeContact(nicerows['Bolagsmän'],true);
    }
    else if ("Komplementär(er)" in nicerows){
        var contact = this.makeContact(nicerows['Komplementär(er)'],true);
    }
    else if("Innehavare" in nicerows){
        var contact = this.makeContact(nicerows['Innehavare'],false);
    }
    else if("Styrelseledamot, verkställande direktör" in nicerows){
        var contact = this.makeContact(nicerows['Styrelseledamot, verkställande direktör'], true);
    }
    else if("Styrelseledamöter" in nicerows){
        var contact = this.makeContact(nicerows['Styrelseledamöter'], true);
    }

As you can see it is a lot of code multiplication just because there are a few possible variables. is there any cleaner way to do this?

4

3 回答 3

6

你可以使用一个循环,或者一个现代的:

var names = ["Bolagsmän", "Komplementär(er)", "Innehavare", "Styrelseledamot, verkställande direktör", "Styrelseledamöter"];
var contact;
names.some(function(name)
{
    if (name in nicerows)
    {
        contact = this.makeContact(nicerows[name], name !== 'Innehavare');
        return true; // Breaks the loop
    }
});

或者无聊的旧类型:

var names = ["Bolagsmän", "Komplementär(er)", "Innehavare", "Styrelseledamot, verkställande direktör", "Styrelseledamöter"];
var contact;
var index, name;
for (index = 0; index < names.length; ++index)
{
    name = names[index];
    if (name in nicerows)
    {
        contact = this.makeContact(nicerows[name], name !== 'Innehavare');
        break;
    }
}

或者可能将标志放在地图中:

var names = {
    "Bolagsmän":                               true,
    "Komplementär(er)":                        true,
    "Innehavare":                              false,
    "Styrelseledamot, verkställande direktör": true,
    "Styrelseledamöter":                       true
};
var name;
var contact;
for (name in names)
{
    if (name in nicerows)
    {
        contact = this.makeContact(nicerows[name], names[name]);
        // Note use of flag -----------------------^
        break;
    }
}
于 2013-08-06T16:20:09.680 回答
0

当对象中只有一个属性时,没有理由列出并尝试所有可能的名称。

for (var name in nicerows)
    var contact = this.makeContact(nicerows[name], name!='Innehavare');
    // break; - not even necessary
于 2013-08-06T17:40:39.493 回答
0

这样的事情怎么样?

var words = {"Bolagsmän": true, "Komplementär(er)": true, "Innehavare": false, "Styrelseledamot, verkställande direktör": true, "Styrelseledamöter": true};

for(var word in words) {
    if(words.hasOwnProperty(word)) {
        if(word in nicerows) {
            var contact = this.makeContact(word, words[word]);
            break;
        }
    }
}
于 2013-08-06T16:18:44.887 回答