javascript - Node.js 中的变量作用域

标签 javascript node.js variables scope

我刚刚开始使用nodeJS,在理解变量范围和引用方面遇到一些困难。例如,在下面的代码中,即使对变量 b 进行了切片,变量 a 也会更改/被覆盖。我的问题是,如何将变量 a 复制到变量 b 而不引用它/覆盖变量 a。

var a = ['a', 'b', 'c', 'd'];
var b = a;
b.splice(3,1);

console.log(a)    //will display ['a', 'b', 'c'] instead of ['a', 'b', 'c', 'd']

最佳答案

不用像阿米特建议的那样使用库,这可以在本地完成,而无需安装巨大的库......

使用不带参数的.slice()

var a = ['a', 'b', 'c', 'd'];
var b = a.slice();
b.splice(3,1);

console.log(a);

当您设置b = a时,您并不是在创建新数组,您只是告诉b保存对a的引用。所以 ab 实际上引用了内存中的同一位置。 .slice 通过返回整个新数组来工作。

关于javascript - Node.js 中的变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30676147/

相关文章:

javascript - 什么时候需要 "javascript: ..."?

javascript - 重复数组

javascript - 为什么我无法使用 JSON 数据在 JS 函数调用上构建树

javascript - 从云功能中的 firebase 存储下载时出错

javascript - promise 不返回对象

javascript - 使用 javascript 和正则表达式删除停用词

php - SQL查询返回混合表

javascript - 两个选择表列

node.js - 如何为 winston 设置唯一的文件名?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP