2012-12-10 52 views
1

我不明白爲什麼我的變量變化數組變量修改的node.js

if(chat.users[i + 1]) 
    console.log("1: " + chat.users[i + 1].username); 
if(save[i+1]) 
    console.log("2: " + save[i + 1].username); 

chat.users[i + 1] = save[i]; 

if(chat.users[i + 1]) 
    console.log("3: " + chat.users[i + 1].username); 
if(save[i+1]) 
    console.log("4: " + save[i + 1].username); 

1: test1 
2: test1 
3: test 
4: test 

我不明白爲什麼我沒有

1: test1 
2: test1 
3: test 
4: test1 

謝謝

編輯:全部代碼是t這裏

http://codepaste.net/gi5ghf (線92)

+0

好的,我做到這一點,這就是工程 \t \t \t \t \t如果(溫度[0])溫度[1] =溫度[0]; \t \t \t \t \t else temp [1] = save [i]; \t \t \t \t \t if(save [i + 1])temp [0] = save [i + 1]; \t \t \t \t \t chat.users [i + 1] = temp [1]; – Ajouve

回答

1

現在你的代碼很清楚!讓我們來看看它

var chat = { 
     users: [ 
      { 
       username: "test" 
      }, 
      { 
       username: "test1" 
      } 
     ] 
    }, 
    // creating reference from save to chat.users 
    save = chat.users, 
    i = 0; 
if (chat.users[i + 1]) { 
    // should be chat.users[1].username ("test1") 
    console.log("1: " + chat.users[i + 1].username); // output "test1" 
} 
if (save[i + 1]) { 
    // should be save[1].username ("test1") 
    console.log("2: " + save[i + 1].username); // output "test1" 
} 

/* 
* creating reference 
* so chat.users[i + 1] is now save[i] ({ username: "test" }) 
* and because save is reference of chat.users, save[i + 1] is now also now save[i] ({ username: "test" }) 
*/ 
chat.users[i + 1] = save[i]; 

if (chat.users[i + 1]) { 
    // should be chat.users[1].username ("test") 
    console.log("3: " + chat.users[i + 1].username); // output "test" 
} 
if (save[i + 1]) { 
    // should be chat.users[0].username ("test") 
    console.log("4: " + save[i].username); // output "test" 
} 

什麼?

讓我再次向您解釋。例如,你有這樣的:

var a = [1, 2]; 

現在你這樣寫:

var b = a; 

也許你想要一個複製到B,而你只創建了一個參考!

那麼看看這個:

console.log(a, b); 
//=> [1, 2] [1, 2] 
a[0] = 3; 

console.log(a, b); 
//=> [3, 2] [3, 2] 

b[0] = 4; 

console.log(a, b); 
//=> [4, 2] [4, 2] 

所以,如果你改變它會爲另一隻也被改變的對象或數組的一個值,因爲它只是一個參考,他們都得到了相同的內存地址。

如果你真的想克隆/複製對象/數組,然後看看this question

+0

對不起,我錯了我的代碼複製,我在我的代碼裏有我到處都是1 + 1 – Ajouve

+0

現在你的代碼很清楚。 – noob

+0

好的,非常感謝我的理解,我必須複製而不是創建參考,謝謝你的鏈接我會看看 – Ajouve

0

節省[I]似乎與 '測試' 的用戶名的用戶。 您要分配此用戶chat.users [I + 1]:

chat.users[i + 1] = save[i]; 

然後打印出它自己的用戶名:

if(chat.users[i + 1]) console.log("3: "+chat.users[i + 1].username); 

最後,將打印出保存[I]」 s用戶名:

if(save[i+1]) console.log("4: "+save[i].username); 

它打印出'test',因爲這就是保存[i]用戶名的原因。

也許你的意思是最後一行打印出保存[i + 1]的用戶名,而不是保存[i]的用戶名?保存[i + 1]確實有用戶名'test1'。

+0

對不起,我錯了我的代碼複製,我在我的代碼裏有i + 1無處不在 – Ajouve