一百万条 IF 语句的替代方案 [英] Alternative to a million IF statements

查看:38
本文介绍了一百万条 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'; }
....

推荐答案

一个 switch 语句,因为你的代码只是 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;
    }

或者当它更简单一些时:

or when it is a bit simpler:

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天全站免登陆