javascript - javascript - 未清除数组引用
问题描述
当我分配 anotherArrayList = arrayList 时,anotherArrayList 是指向 arrayList 的指针。那么为什么当我清空arrayList 时这不起作用。
var arrayList = ['a', 'b', 'c', 'd', 'e', 'f'];
var anotherArrayList = arrayList;
arrayList[1] = '15';
console.log(arrayList); // output: [ "a", "15", "c", "d", "e", "f" ]
console.log(anotherArrayList); // output: [ "a", "15", "c", "d", "e", "f" ]
arrayList = [];
console.log(arrayList); // output: []
console.log(anotherArrayList); // output: [ "a", "15", "c", "d", "e", "f" ]
解决方案
通过分配一个新数组,旧对象引用获得对空数组的新引用。
您也可以将零分配给length
清空对象引用的属性。
var arrayList = ['a', 'b', 'c', 'd', 'e', 'f'],
anotherArrayList = arrayList;
arrayList[1] = '15';
console.log(arrayList); // [ "a", "15", "c", "d", "e", "f" ]
console.log(anotherArrayList); // [ "a", "15", "c", "d", "e", "f" ]
arrayList.length = 0;
console.log(arrayList); // []
console.log(anotherArrayList); // []
推荐阅读
- javascript - 当我的应用程序在两个不同的选项卡中打开时如何控制它
- react-native - 再次渲染 react-native 应用程序 Web-View
- angular - 创建一个通用验证器以防止在文本区域中粘贴数据期间添加换行符 + Angular 8
- regex - 如何将所有正则表达式匹配到字符串列表中
- python - 在 Python 中并行化数据提取和处理的方法
- express - NestJS - 如何使用 TypeOrm 正确更新
- javascript - 我如何在反应 js 中渲染 Mathjax 表达式,我使用的是 mathjax.org?
- laravel - laravel 多级关系急切加载尝试从子模型重新访问父模型的问题
- winapi - 更改平面滚动条的颜色(FlatSB_SetScrollProp 函数中的自定义调色板)
- postgresql - 这是什么“错误:不明确的列引用错误”?