简体   繁体   English

重新分配不会改变 java 脚本中 const 的值吗?

[英]Is reassignment not changing value of const in java script?

Please clarify this silly doubt:请澄清这个愚蠢的疑问:

for (let count = 0; count < 3 && count < players.length; count++) { 
  const num = count + 1  
  const player = players[count] 
  console.log(`${num}. ${player}`) 
}

Here const num= count+1;这里 const num= count+1; isnot new value (primitive)being assigned to count in each iteration.不是在每次迭代中将新值(原始值)分配给计数。 or const num is allowed as it ll create new variable with same name discarding old var const num=0;或 const num 是允许的,因为它将创建具有相同名称的新变量,丢弃旧的 var const num=0; num=count+1 will be invalid i understand but can some one explain above doubt.我理解 num=count+1 将是无效的,但有人可以解释上述疑问。

In this case you create new const num in each iteration, that is mean you are not changing existed variable.在这种情况下,您在每次迭代中创建新的const num ,这意味着您不会更改现有变量。 There is could other case when you have const num before the loop, then you can't change it in the loop, so you should use let.可能还有其他情况,当你在循环之前有const num ,那么你不能在循环中改变它,所以你应该使用 let。 It's better use const for primitive values.最好将 const 用于原始值。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM