简体   繁体   English

为什么在ruby循环中var起作用但const不起作用?

[英]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 at all. 这就是常量在ECMAScript中的工作方式,实际上与毫无关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么const app = App || {}; 工作但使用var呢? - Why doesn't const App = App || {}; work but using var does? 关于var / const,为什么这段代码会起作用? - About var/const, why this code will work? 在for循环中var i = [0],然后递增i ++ - 为什么它有效? - var i = [0] in a for loop, then incremented i++ - why does it work? 为什么在全局范围内的 for-of 循​​环中使用 const 会抛出 TypeError,但在函数中它起作用? - Why does using const in a for-of loop in global scope throw TypeError, but within a function it works? 为什么JSLint不允许在for循环中使用“var”? - Why does not JSLint allow “var” in a for loop? 为什么有效? JS 函数和 var - Why does it work? JS function and var "JavaScript 中的变量,为什么放 `var` 不起作用?" - Variable in JavaScript, why putting `var` does not work? 为什么此regexp可以作为var pattern = /…/而不作为var pattern = RegExp(“…”)使用? - Why does this regexp work as var pattern = / … / but not as a var pattern = RegExp(“…”)? 为什么 const 比 var 慢? - Why is const slower than var? 为什么在该示例中,“ for循环”与“ let”一起使用,而不与“ var”一起使用? - why in the example the “for loop” work well with “let”, and not work with “var”?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM