替代百万IF语句 [英] Alternative to a million IF statements

查看:97
本文介绍了替代百万IF语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JavaScript我将网页中的名称拉出来并以某种方式将它们串在一起(可能与数组一起)。一旦我将所有名称收集在一起,我需要创建另一个字符串,该字符串提供名称的所有电子邮件地址。电子邮件地址不在网页上,所以我必须以某种方式在我的脚本中列出每个可能的thisName = thisEmail。我打算通过制作一个无数的if语句来解决这个问题,但我认为必须采用更有效的方式。有什么建议吗?

Using JavaScript I am pulling names out of webpage and stringing them together somehow (probably going with an array). Once I gather all the names together I need to make another string that gives all the email addresses of the names. The email addresses are not on the webpage so I will have to list every possible thisName=thisEmail in my script somehow. I was about to approach this with making a bazillion if statements but I thought there has to be a more efficient way. Any suggestions?

var x = getElementById("names");
var name = x.InnerHTML;
var email;
if (name == 'Steve'){ email == 'steve462@gmail.com'; }
if (name == 'Bob'){ email == 'duckhunter89@gmail.com'; }
....


推荐答案

开关声明,因为你的代码只有if-elses: - )

A switch statement, as your code is only if-elses :-)

不,老实说。最好的办法是,如果您找到一个简单的算法来创建任何给定名称的电子邮件地址,例如

No, honestly. The best thing would be if you'd find a simple algorithm to create an email address from any given name, like

function mail(name) {
    return name.toLowerCase() + "@gmail.com";
}
var email = mail("Bob") // example usage

如果它们差异很大,您可以使用对象作为键值映射:

If they differ to much, you might use an object as a key-value-map:

var mails = {
    "Steve": "steve@gmail.com",
    "Bob": "bob1@freemail.org",
    ...
}
var email = mails[name];

如果你必须确定需要使用哪种算法,你也可以将它们结合起来:

You could also combine those, if you have to determine which algorithm you need to use:

var map = [{
    algorithm: function(name) { return name+"@something"; },
    names: ["Steve", "Bob", ...]
},{
    algorithm: function(name) { return "info@"+name+".org"; },
    names: ["Mark", ...]
}];
for (var i=0; i<map.length; i++)
    if (map[i].names.indexOf(name) > -1) {
        var email = map[i].algorithm(name);
        break;
    }

或稍微简单一点:

var domains = {
    "gmail.com": ["Steve", "Bob", ...],
    "free.xxx": ["Mark", ...],
    ...
};
for (var domain in domains)
    if (domains[domain].indexOf(name) > -1)
        var email = name.toLowerCase()+"@"+domain;
        break;
    }

尝试减少要交付给客户端的数据量你可以。

Just try to reduce the amount of data to deliver to the client as much as you can.

这篇关于替代百万IF语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆