我需要对一个变量调用多个转换方法。在 JavaScript 中,有哪些干净的方法可以做到这一点?是否过度设计它来创建一个类,以便我可以进行方法链接?
这是我想要整理的示例:
let value = 'foo';
value = transformValueFn1(value);
value = transformValueFn2(value);
value = replaceCertainChars(value);
value = encodeAsHtml(value);
// etc
return value
最佳答案
在变压器数组上使用reduce
let value = 'foo';
const newValue = [
transformValueFn1,
transformValueFn2,
replaceCertainChars,
encodeAsHtml
].reduce((val, fn) => fn(val), value)
function transformValueFn1(val) {
console.log('transformValueFn1', val);
return val;
}
function transformValueFn2(val) {
console.log('transformValueFn2', val)
return val;
}
function replaceCertainChars(val) {
console.log('replaceCertainChars', val)
return val;
}
function encodeAsHtml(val) {
console.log('encodeAsHtml', val)
return val;
}
If you're doing this more than once or twice, a class would make the most sense IMO, though you could also use an array of the functions and reduce – CertainPerformance
关于javascript - 调用多种转换方法的更简洁的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57492765/