【问题标题】:Will the memory which store the old variable be free when reassign the variable in Nodejs?在Nodejs中重新分配变量时,存储旧变量的内存是否会空闲?
【发布时间】:2019-01-16 01:31:18
【问题描述】:

在下面的代码中

a = 1
b = {"a": a} // this output {"a": 1}
a = 2
console.log(b) // this still output {"a": 1}

在这种情况下,存储1内容的内存在重新赋值给2时会空闲吗?

【问题讨论】:

标签: javascript node.js variables lifetime


【解决方案1】:

变量在销毁之前不会丢失其内存空间。

当你写作时

  a = 1
  b = {"a": a}        

a 的值被分配给对象 ba 节点。 a 变量未绑定到 a 节点。如果您想将节点 a 更新为新值,您可以执行以下操作:

  b.a = 2;        
  console.log(b.a); //will print 2        

【讨论】:

    【解决方案2】:
    b = {"a": a} // this output {"a": 1}
    

    这条指令告诉编译器创建一个新对象并将键“a”设置为变量a现在的值,因此值1被复制到b的内存中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 2014-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 2014-08-03
      相关资源
      最近更新 更多