Conditionally initializing a constant in Javascript(在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.
这篇关于在Javascript中有条件地初始化一个常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在Javascript中有条件地初始化一个常量
基础教程推荐
- Bokeh Div文本对齐 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
