简体   繁体   English

Javascript:简单但奇怪的数组行为?

[英]Javascript: Simple yet weird behavior with arrays?

Test 1: 测试1:

var arr1 = [10, 20];
var arr2 = arr1;

arr2[0]++;

alert(arr1);// [11, 20] --- What?!?!
alert(arr2);// [11, 20] --- correct

Test 2: 测试2:

var arr1 = [10, 20];
var arr2 = [arr1[0], arr1[1]];

arr2[0]++;

alert(arr1);// [10, 20] --- correct
alert(arr2);// [11, 20] --- correct

In test 1, Why the first array's first element was changed? 在测试1中,为什么更改了第一个数组的第一个元素? As far as I know, in other OOP languages like Java & PHP, if we do the Test 1's var arr2 = arr1; 据我所知,在其他OOP语言(如Java和PHP)中,如果执行测试1,则var arr2 = arr1; this is called "referencing", once we change something with the new variable's value, it creates a new value for that so the first reference "arr1" doesn't get effected. 这称为“引用”,一旦我们使用新变量的值更改了某些内容,它就会为此创建一个新值,因此第一个引用“ arr1”不会生效。 Why it's not the same thing in Javascript!? 为什么在Javascript中不一样呢? This totally doesn't make sense! 这完全没有道理! Is it a bug? 是虫子吗? or it's just that Javascript behaves differently? 还是只是Javascript的行为有所不同?

JavaScript variables refer to objects. JavaScript变量引用对象。 When a variable "is" an object, it contains a reference to the object. 当变量“是”对象时,它包含对该对象的引用。 Assigning the value of such a variable to another variable just transfers the reference; 将这样一个变量的值赋给另一个变量只会传输引用。 it does not make a copy of the referenced object. 没有被引用的对象的副本。

In the Test 1 both variables are referencing the same array object, so anything you do on one is going to be reflected on the other one. 在测试1中,两个变量都引用同一个数组对象,因此对一个变量所做的任何操作都将反映在另一个变量上。

On the other hand, on the Test 2 you are copying the values into a new array, so each variable is referencing different array objects. 另一方面,在测试2上,您正在将值复制到新数组中,因此每个变量都引用了不同的数组对象。

edit: to remove the "passby" term. 编辑:删除“通过”一词。

edit 2: on a side note, this happens in java too. 编辑2:在旁注,这也发生在Java中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM