[英]Why does var work but not const within ruby loop?
I'm trying to toggle each untagged task. 我正在尝试切换每个未标记的任务。 This works, 这样有效
<% @untagged.each do |task| %>
var task_id = <%= task.id %>;
$(`#${task_id}`).fadeToggle();
<% end %>
But, quite curiously this doesn't. 但是,很奇怪,事实并非如此。
<% @untagged.each do |task| %>
const task_id = <%= task.id %>;
$(`#${task_id}`).fadeToggle();
<% end %>
From my understanding, every loop creates a new block. 据我了解,每个循环都会创建一个新块。 The constant declaration will be nested in each of these blocks, thus there wouldn't be any redeclarations. 常量声明将嵌套在每个这些块中,因此不会有任何重新声明。 So why is the second example not working? 那么为什么第二个示例不起作用?
Thank you in advance! 先感谢您!
What does your code do? 您的代码做什么?
For every element in @untagged
, it generates the following lines of code: 对于@untagged
每个元素,它将生成以下代码行:
const task_id = FOO;
$(`#${task_id}`).fadeToggle();
with FOO
replaced by the element's ID. 用FOO
替换为元素的ID。 Let's assume, @untagged
looks like this: [<#Task @id = 23>, <#Task @id = 24>]
, then the generated code will look like this: 假设@untagged
看起来像这样: [<#Task @id = 23>, <#Task @id = 24>]
,那么生成的代码将如下所示:
const task_id = 23;
$(`#${task_id}`).fadeToggle();
const task_id = 42;
$(`#${task_id}`).fadeToggle();
In ECMAScript, const
ants can only be declared and assigned once, ergo, you get a static error. 在ECMAScript中, const
只能声明和分配一次,因此,您会遇到静态错误。 That's just how constants work in ECMAScript and doesn't really have anything to do with ruby-on-rails at all. 这就是常量在ECMAScript中的工作方式,实际上与ruby-on-rails毫无关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.