[英]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.