我有这段代码:
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
。关于动态创建变量有一些问题,但它们通常具有相同的名称+我从未见过它们与自定义函数结合使用。
有什么提示吗?
最佳答案
我已根据 Ates Gora、Thomas、Bergi 的提示更新了此答案。
使用 ES2016 中实现的一些功能,解决方案可能如下所示:
foo.bar('run', function () {
return myCustomFunction(
...[ 'text1', 'textLong', 'text' ].map(fileName => {
return 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'));
});
);
});
关于javascript - 从数组(forEach)生成代码块(函数、变量)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41677687/