2017-02-11 64 views
1

我有這個數組聲明如下:使用此陣爲什麼這個數組沒有被要求改變它的值?

var gamme = 
[ 
    ["A"], 
    ["A♯","B♭"], 
    ["B","C♭"], 
    ["C","B♯"], 
    ["C♯","D♭"], 
    ["D"], 
    ["D♯","E♭"], 
    ["E","F♭"], 
    ["F","E♯"], 
    ["F♯","G♭"], 
    ["G"], 
    ["G♯","A♭"], 
]; 

,我生成另一個數組。 我想temperamentEgal看起來像這樣: 例如:

temperamentEgal[10] = [103.82617439498631, ["G♯","A♭"]] 
temperamentEgal[25] = [233.08188075904502, ["A♯","B♭"]] 

所以這是我做的:

base = pow(2,1/12); // 2^(1/12) 
for (i=0; i<12*octaves; i++) // octaves = 6 
{ 
    temperamentEgal[i] = [] 
    temperamentEgal[i][0] = 55*pow(base,i); // = 138.6 
    temperamentEgal[i][1] = gamme[i%12]; // = ["C♯","D♭"] 
    console.log("gamme["+i%12+"] = " + gamme[i%12]); 
    for (j=0; j<temperamentEgal[i][1].length; j++) 
    { 
     var octaveNote = 1+i/12; 
     octaveNote = floor(octaveNote); 
     temperamentEgal[i][1][j] += str(octaveNote); 
    } 
} 

正如你所看到的,在任何時候,我改變的gamme值 儘管如此,隨着循環的進行,我是從的console.log得到這個:

gamme[0] = A 
gamme[1] = A♯,B♭ 
gamme[2] = B,C♭ 
gamme[3] = C,B♯ 
gamme[4] = C♯,D♭ 
gamme[5] = D 
gamme[6] = D♯,E♭ 
gamme[7] = E,F♭ 
gamme[8] = F,E♯ 
gamme[9] = F♯,G♭ 
gamme[10] = G 
gamme[11] = G♯,A♭ 
gamme[0] = A1 
gamme[1] = A♯1,B♭1 
gamme[2] = B1,C♭1 
gamme[3] = C1,B♯1 
gamme[4] = C♯1,D♭1 
gamme[5] = D1 
gamme[6] = D♯1,E♭1 
gamme[7] = E1,F♭1 
gamme[8] = F1,E♯1 
gamme[9] = F♯1,G♭1 
gamme[10] = G1 
gamme[11] = G♯1,A♭1 

如果我合作它不會再發生變化temperamentEgal[i][1][j] += str(octaveNote);

爲什麼要更改temperamentEgal[i][1]的值也會更改gamme[i%12]的值?

回答

2

,而你不改變gamme,你改變這條線所引用的匿名數組:

temperamentEgal[i][1] = gamme[i%12]; 

兩個右側和左側這項任務現在指向同一個Array對象 - 如果你想修改數組的副本,你應該複製的數組的值,而不是參考Array對象:

ES5:temperamentEgal[i][1] = gamme[i%12].slice();

ES6:temperamentEgal[i][1] = [...gamme[i%12]]使用spread operator

相關問題