有条件地在Javascript中初始化常量 [英] Conditionally initializing a constant in Javascript

查看:99
本文介绍了有条件地在Javascript中初始化常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ES6以后我们有 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 statement 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 statement 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中初始化常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆