相关疑难解决方法(0)

JavaScript中是否有常量?

有没有办法在JavaScript中使用常量?

如果没有,指定用作常量的变量的常见做法是什么?

javascript constants

1118
推荐指数
19
解决办法
48万
查看次数

当在if()或try {} catch(e){}中时,为什么const在多次运行代码时抛出错误?

我正在尝试使用声明一堆常量const。我的问题是,在Firebug控制台中测试代码会引发错误,抱怨“ const foo的重新声明”。

我尝试将其包装在一个 try{}catch(e){}块中,但这无济于事,即使尝试使用以下代码来解决它(张贴减去所有console.info()“调试”的调用以求清楚),它仍然会引发错误第二次运行时:

if(!chk_constsDeclaredYet) {
  var chk_constsDeclaredYet = true;
  const foo="bar";
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,当const位于if(){}中时,当第二次运行代码时,为什么还要查看const foo?

注意:代码将在firebug javascript控制台中运行,而我想要实现的工作流程是:

  1. 将代码粘贴到Firebug控制台中
  2. 命中运行(创建常量)
  3. 我在不重新加载页面的情况下对控制台中的代码进行了编辑(常量仍在页面上下文中定义)
  4. 再次命中运行(使用if(){}以避免在前一次运行已声明常量的情况下重新声明常量)
  5. 从(3)重复

萤火虫输出:

//FIRST RUN::
>>> console.group() console.info('--code start--'); ...console.info('--code end--'); console.groupEnd()
--code start--
chk_constsDeclaredYet = undefined
foo = undefined
--if()--
--if() running..--
--end if()--
chk_constsDeclaredYet = true
foo = bar
--code end--

//SECOND RUN::
>>> console.group() console.info('--code start--'); ...console.info('--code end--'); console.groupEnd()
TypeError: redeclaration of const foo { message="redeclaration of const foo", more...}
Run Code Online (Sandbox Code Playgroud)

javascript firebug const constants

3
推荐指数
1
解决办法
5696
查看次数

标签 统计

constants ×2

javascript ×2

const ×1

firebug ×1