[英]JavaScript: How can I get and use a value multiple times in an expression
我经常发现自己有一个值,后跟一个表达式,该表达式要么多次使用该值,要么同时使用该表达式并返回它。 例如:
const errorCode = getErrorCode();
return new Error(`Error ${errorCode}: ${getErrorMessage(errorCode)}`);
const foo = getFoo();
return [getBar(foo), getBaz(foo)]; // Assume that I cannot make a function getBarAndBaz(foo)
const result = getResultOrNull();
return result
? result
: getAlternative();
我希望能够避免将值分配给变量,以便我可以将它们转换为一个衬垫。
如果我假设它的语法看起来像什么,我可以看到它类似于以下之一:
return new Error(`Error ${errorCode}: ${getErrorMessage(errorCode)}`), where errorCode = getErrorCode();
return (getFoo(), getBar()) -> { foo: $1, bar: $2, baz: getBaz($1, $2)};
这两个想法看起来都类似于立即调用的函数表达式 (IIFE),只是参数是计算出来的而不是传入的。 因此,我可以使用带有默认值或闭包的 IIFE:
(
(foo = getFoo(), bar = getBar()) => ({ foo, bar, baz: getBaz(foo, bar)})
)()
(
() => {
const foo = getFoo();
const bar = getBar();
return (
() => ({ foo, bar, baz: getBaz(foo, bar) })
)();
}
)()
然而,这两个看起来都有些凌乱。
我可以使用 do 表达式( https://github.com/tc39/proposal-do-expressions ):
do {
const foo = getFoo();
const bar = getBar();
{ foo, bar, baz: getBaz(foo, bar) };
};
但是,do 表达式还不是 JavaScript 的一部分,如果能找到一种真正的单行表达式,那就太好了。
一种衬里,当然虽然丑陋:
function getFoo() {
return 'FOO';
}
function getBar() {
return 'BAR';
}
function getBaz(...args) {
return args;
}
let result;
if (1) { let foo = getFoo(); let bar = getBar(); result = { foo, bar, baz: getBaz(foo, bar) };}
console.log(result);
// { foo: 'FOO', bar: 'BAR', baz: [ 'FOO', 'BAR' ] }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.