将代码减少为一个字符串

时间:2014-10-23 17:01:28

标签: javascript

blocks['package'].fadeIn();
blocks['optional'].fadeIn();
blocks['setup1'].fadeIn();
blocks['payment'].fadeIn();

如何将此代码优化为一般行为,尝试类似:

blocks['package', 'optional', 'setup1', 'payment'].fadeIn();

1 个答案:

答案 0 :(得分:3)

像Underscore.js或lodash这样的库使这种事情变得简单,但你也可以通过简单的循环轻松完成:

var fades = ['package', 'optional', 'setup1', 'payment'];
for (var i = 0; i < fades.length; i++) {
  blocks[fades[i]].fadeIn();
}