在Javascript中有条件地初始化一个常量
从 ES6 开始,我们有 const
.
ES6 onwards we have const
.
这是不允许的:
const x; //declare first
//and then initialize it
if(condition) x = 5;
else x = 10;
这是有道理的,因为它阻止我们在初始化之前使用常量.
This makes sense because it prevents us from using the constant before it's initialized.
如果我这样做了
if(condition)
const x = 5;
else
const x = 10;
x 变为块作用域.
那么如何有条件地创建一个常量呢?
So how to conditionally create a constant?
推荐答案
如您所知,您的问题是 const
必须在声明它的相同表达式中初始化.
Your problem, as you know, is that a const
has to be intialised in the same expression that it was declared in.
这并不意味着您分配给常量的值必须是文字值.它实际上可以是任何有效的表达式 - 三元:
This doesn't mean that the value you assign to your constant has to be a literal value. It could be any valid expression really - ternary:
const x = IsSomeValueTrue() ? 1 : 2;
或者也许只是将它分配给一个变量的值?
Or maybe just assign it to the value of a variable?
let y = 1;
if(IsSomeValueTrue()) {
y = 2;
}
const x = y;
您当然也可以将其分配给函数的返回值:
You could of course assign it to the return value of a function, too:
function getConstantValue() {
return 3;
}
const x = getConstantValue();
因此,有很多方法可以使值动态化,您只需要确保它只分配在一个地方.
So there's plenty of ways to make the value dynamic, you just have to make sure it's only assigned in one place.
相关文章