【问题标题】:number not getting added and printed in for loop没有在 for 循环中添加和打印数字
【发布时间】:2022-12-09 08:30:02
【问题描述】:

我测试了一些代码,我的程序需要一个逻辑,但是我在一个单独的 arquive 中进行了测试,我遇到了以下问题:

let numero = 0;
const string = `aaa: ${numero}`

for(let i=0; i<3;i++) {
  console.log(string)
  numero += 1
}

console.log(numero)

但结果是这样的:

aaa: 1
aaa: 1
aaa: 1
4
  • 为什么循环添加 ,但在字符串中继续使用值 1?

有人可以解释我的错误是什么? javascript 有时真的很奇怪 xD

【问题讨论】:

  • 字符串的值不是动态的。即使numero的值改变了,字符串的值也不会改变。
  • 在循环内移动const string = `aaa: ${numero}`
  • 哦,我明白了,谢谢大家!

标签: javascript node.js


【解决方案1】:

在 for(let i=0; i<3;i++) 之后写入 string = aaa: ${numero}

它这样做的原因是因为 numero 在 for 循环中发生了变化,但字符串是在 for 循环之外声明的,因此是常量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    相关资源
    最近更新 更多