我有一个函数,该函数的值将始终需要转换。我想知道是否有一种方法可以在值到达函数体之前获取值并使用某些除法?现在,我正在体内进行分裂,但总是在寻找一种新的更好的做事方法:
// 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个参数调用该函数,这就会按预期工作。我建议您不过只是在函数内部进行除法。