gpt4 book ai didi

javascript - JS如何用单行设置范围之外的值

转载 作者:行者123 更新时间:2023-12-01 00:15:35 24 4
gpt4 key购买 nike

如果函数 calculateAvgGainLoss回复包括 avgGain, avgLoss我们可以这样得到这些值。

const { avgGain, avgLoss } = calculateAvgGainLoss(prices);

我想将这些值设置为在函数外部定义的变量。我怎样才能做到这一点 ?下面的例子。

describe("test", () => {
let avgGain: number, avgLoss: number;
it("Calculate average gain & loss", () => {
const prices = [...];
/*...This isn't working, has to be changed...*/ { avgGain, avgLoss } = calculateAvgGainLoss(prices);
expect(avgGain).toBe(0.24);
expect(avgLoss).toBe(0.1);
});

});

最佳答案

{ 开头会混淆解析器(它是作用域的开头吗?对象?等等)。只需用括号将行括起来即可绕过此问题:

describe("test", () => {
let avgGain: number, avgLoss: number;
it("Calculate average gain & loss", () => {
const prices = [...];
({ avgGain, avgLoss } = calculateAvgGainLoss(prices)); // <--
expect(avgGain).toBe(0.24);
expect(avgLoss).toBe(0.1);
});

});

关于javascript - JS如何用单行设置范围之外的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59788789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com