1

我正在学习 JavaScript。我很困惑下面的例子是如何工作的?我创建了一个对象person,并将其值分配给Person2.

var person = "hello";  
var Person2 = person; 
person = "hey"; 

console.log(Person2); // prints hello
console.log(person); //prints hey

为什么Person2即使person已经分配了新值,值也没有改变。是因为我传递了一个引用。我不清楚它的实施。我错过了什么概念?

4

5 回答 5

2

You are dealing with a primitive in JavaScript - a string is a primitive (so is a boolean, number, undefined and null). The primitives are assigned by value, not by reference.

Arrays and objects are assigned by reference.

var person = ['test'];
var person2 = person;
person[0] = 'hi';

console.log(person); //['hi'];
console.log(person2); //['hi'];
于 2013-10-14T16:27:36.023 回答
1

让我们逐步了解您的代码中发生的事情......

1: var person = "hello";  
2: var Person2 = person; 
3: person = "hey"; 
4: console.log(Person2);
5: console.log(person);
  1. person 被分配了对新字符串对象“hello”的引用。
  2. Person2 是通过引用现有字符串“hello”来分配的。
  3. person 被分配了对新字符串对象“hey”的引用。
  4. Person2 指向“hello”字符串,所以这是输出
  5. 人指向“嘿”字符串,所以这是输出
于 2013-10-14T16:30:51.260 回答
0

You are setting the value of person2 to the value of person, then you are changing the value of person afterward. The value of person2 will not change.

于 2013-10-14T16:26:12.360 回答
0

Strings and numbers (primitives) are NOT passed by reference, this is only the case with objects or array (arrays are objects strictly). So assigning it to a new variable COPIES the string.

To pass it by reference you would use something like

var person = {message: "hello"};
var Person2 = person;
person.message = "Hey";

person === Person2 // true
于 2013-10-14T16:26:15.373 回答
0

这是因为您没有传递引用(至少,不是指向的person

您尚未更改 的值,Person2因此该值仍然"hello"是您分配给它的唯一值。

于 2013-10-14T16:25:23.687 回答