使 JavaScript 代码变得干燥的最优雅的方法
这是我想要干燥的 JavaScript 代码片段:
if(agency == 'abcd')map.entities.push(abcd);
if(agency == 'efgh')map.entities.push(efgh);
if(agency == 'xyz')map.entities.push(xyz);
if(agency == 'pqrs') map.entities.push(pqrs);
if(agency == 'values')map.entities.push(values);
现在将来可能会有更多针对不同键的 if。JavaScript 不提供我可以在此处使用的 HashMap 构建。使用数组和 id 之类的东西来使其干燥也太俗气了。 有没有更简单的解决方案?可能是这样的
if(agency == 'abcd')map.entities.push(stringToVariable('abcd'));
,然后我可以使用 for 并遍历键。我不确定这在 JavaScript 中是否可能。
Here is a snippet of my JavaScript Code that I want to DRY up:
if(agency == 'abcd')map.entities.push(abcd);
if(agency == 'efgh')map.entities.push(efgh);
if(agency == 'xyz')map.entities.push(xyz);
if(agency == 'pqrs') map.entities.push(pqrs);
if(agency == 'values')map.entities.push(values);
Now in future may have more ifs for different keys coming in. JavaScript doesnt offer a build in HashMap which i can use here. And using arrays and id stuff to make it DRY is too tacky.
Is there a more simpler solution to this? May be something like this
if(agency == 'abcd')map.entities.push(stringToVariable('abcd'));
then I can just use a for and iterate through the keys. I am not sure though this possible at all in JavaScript.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
也许吧:
对我来说,这种情况需要退后一步,重新思考更多情况,因为它本质上是丑陋的。为什么存在所有这些单独的变量,而不是具有与“代理”值相对应的键的单个对象?
Well maybe:
To me, this is a situation that calls for stepping back and re-thinking more of the situation, as it's just inherently ugly as it stands. Why are there all these separate variables, instead of a single object with keys corresponding to "agency" values?
只要您知道
agency
值是干净的,就可以在此处使用eval
:There's a legitimate case for using
eval
here as long as you knowagency
values are clean:javascript 中的每个对象都是一个 hashmap(至少是一个 hashmap),这就是这段代码返回 true 的原因:
因此,您可以做的是构建一个返回值/函数的对象,如下所示:
然后执行
如果所有变量都是静态的你可以做得更简单,就像这样:
Every object in javascript IS a hashmap (at least sort of a hashmap), that's why this code returns true:
So, what you can do is build up an object of returnvalues/functions like so:
And then do
If all your variables are statics you can do it even simpler, like so:
_inArr 函数在每个主要的 javascript 包中都可用(例如 $.inArray)。
我认为重点是 JavaScript 是一个很大的哈希图。例如,全局函数名称只是窗口对象的一个键。对于任何命名空间项目也是如此。
The _inArr function is available in every major javascript package ($.inArray, for example).
I think the point is that JavaScript is a big hashmap. A global function name, for instance, is just a key into the window object. The same goes for any namespaced items.
假设代理的所有可能值都作为变量存在。
Assumes all possible values of agency exist as variables.