【发布时间】:2017-01-16 13:38:28
【问题描述】:
我有这段代码:
foo.bar('run', function () {
var text1 = foo.url('./src/url/text1.txt')
.go(bar.do({ something }))
.also(bar({
variable: 1,
else: 2,
}).on('exception', doSomething ))
.also(bar.url('.src/url/source'))
var textLong = foo.url('./src/url/textLong.txt')
.go(bar.do({ something }))
.also(bar({
variable: 1,
else: 2,
}).on('exception', doSomething ))
.also(bar.url('.src/url/source'))
var text = foo.url('./src/url/text.txt')
.go(bar.do({ something }))
.also(bar({
variable: 1,
else: 2,
}).on('exception', doSomething ))
.also(bar.url('.src/url/source'))
return myCustomFunction(text1, textLong, text);
}
您可以看到它尽可能地抗 DRY,每个变量都是相同的,除了变量名和文件名 (foo.url)。
我一直想知道是否有可能使它更简单,例如:
var files = [ 'text1', 'textLong', 'text'];
然后:
foo.bar('run', function () {
files.forEach(function(fileName){
var fileName = foo.url('./src/url/'+ fileName + '.txt')
.go(bar.do({ something }))
.also(bar({
variable: 1,
else: 2,
}).on('exception', doSomething ))
.also(bar.url('.src/url/source'))
})
return myCustomFunction(text1, textLong, text);
})
但我可以通过第二种方法获得的最佳效果是text1 is not defined。 SO上有一些关于动态创建变量的问题,但它们通常具有相同的名称+我从未见过它们与自定义函数结合使用。
有什么提示吗?
【问题讨论】:
标签: javascript loops foreach eval