gpt4 book ai didi

javascript - 是否可以在定义之前在表达式中使用默认参数?

转载 作者:行者123 更新时间:2023-12-02 22:31:45 25 4
gpt4 key购买 nike

我有一个函数,它的值始终需要转换。我想知道是否有一种方法可以在它到达函数体之前获取该值并使用一些除法?现在我正在 body 中进行划分,但总是寻找一种新的更好的做事方式:

// Prices come in the the form of thousands (e.g. 24 => 2400) so division is necessary here
const formatPrice = (price = (price / 100), commaSeparated = true) => {
if (commaSeparated) {
return value.toLocaleString('en-GB', {
minimumFractionDigits: 2
});
}

return value;
}

通过上述我会得到错误:

'price' was used before it was defined

最佳答案

虽然这并不是最好的方法,但一种可能的方法是添加一个额外的参数并使用其默认值作为表达式,如下所示:

const formatPrice = (price, commaSeparated = true, dividedPrice = price / 100) => {
}

只要您不使用 3 个参数调用该函数,这就会按预期工作。我建议您只需在函数内部进行除法即可。

关于javascript - 是否可以在定义之前在表达式中使用默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58878255/

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