我正在尝试更好地理解引用传递如何与拼接相关。我想要一个主对象数组,并使用另一个引用主数组对象的数组。例如:
var mainArray = [
someObject,
anotherObject
]
var subArray = [];
subArray.push( mainArray[ 0 ] );
我不明白的是如果我拼接原始值会发生什么?
mainArray.splice( 0, 1 );
是否子数组[0]:
- 也被拼接了?
- 值仍然存在,因为有指向它的指针?
- 留下一个空值?
最佳答案
在这段代码之后:
var mainArray = [
someObject,
anotherObject
];
var subArray = [];
subArray.push( mainArray[ 0 ] );
...你在内存中的内容看起来有点像这样:
+−−−−−−−−−−+ someObject−−−−−−−−−−−−−−−−−−+−−+−−−−−−−−−−−−−−−−−−>| (object) | / / +−−−−−−−−−−+ | | | | +−−−−−−−−−−+ | | anotherObject−−−+−>| (object) | | | / +−−−−−−−−−−+ | | | +−−−−−−−−−−−+ | | | subArray−−−−>| (array) | | | | +−−−−−−−−−−−+ | | | | length: 1 | | | | | 0: |−/ | | +−−−−−−−−−−−+ | | | | +−−−−−−−−−−−+ | | mainArray−−−−>| (array) | | | +−−−−−−−−−−−+ | | | length: 2 | | | | 0: |−−/ | | 1: |−−−−−−−−−−−−−−−−−−−−/ +−−−−−−−−−−−+
Note that there is no connection between mainArray
and subArray
at all. They both just happen to contain the same value (which is also the value in someObject
, all three places have an object reference for the same object).
Removing that value from mainArray
has no effect on subArray
(or on the objects):
mainArray.splice(0, 1);
+−−−−−−−−−−+ someObject−−−−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−>| (object) | / +−−−−−−−−−−+ | | +−−−−−−−−−−+ | anotherObject−−−+−>| (object) | | / +−−−−−−−−−−+ | | +−−−−−−−−−−−+ | | subArray−−−−>| (array) | | | +−−−−−−−−−−−+ | | | length: 1 | | | | 0: |−/ | +−−−−−−−−−−−+ | | +−−−−−−−−−−−+ | mainArray−−−−>| (array) | | +−−−−−−−−−−−+ | | length: 1 | | | 0: |−−−−−−−−−−−−−−−−−−−−/ +−−−−−−−−−−−+
因此基于此:
1. also get spliced?
不,改变 mainArary
的内容对 subArray
没有影响。
2. the value still exist since there is a pointer to it?
subArray
条目 0
的值不受影响。
3. get left with an empty value?
不,对 subArray
根本没有影响。
I am trying to better understand how pass by reference works in relation to splice.
您混淆了“引用”一词的两种不同含义(很多人都这样做)。
“按引用传递”是编程中的一个术语。也就是说,它具有特定的含义:将对变量 的引用传递给函数,这样函数就可以访问并更改该变量的内容。 JavaScript 没有传递引用。
你在问题中处理的是对象引用,它与传递引用无关,只是这两个概念都包含“引用”一词(但在关系完全不同的东西。)
对象引用是值。它们告诉 JavaScript 引擎对象在内存中的位置。
关于javascript - 通过引用和拼接传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43633921/