-1

Today I have found one weird behavior of JS regarding Array. I was trying to build AES-128 and the problem was with the function shiftRows(). I am working on 1D representation (16) of 2D array (4 * 4) and trying to left shift elements by some amount.

Whenever I try printing in console only it is OK. But whenever I change an element of any array S or X (temporary copy of S) it changes the whole return values as well as previous printing values. I don't know what is my browsers doing. Please Help Me.

Testing phase-1:

function shiftRows(S) {
    var X = S;
    console.log(X);
    var p;
    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            p = (4 - i + j) % 4;
            console.log(p, X[4 * i + p]);
            // X[4 * i + j] = S[4 * i + p];
        }
    }
    return S;
}
var A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
console.log(shiftRows(A));

Testing phase-2:

function shiftRows(S) {
    var X = S;
    console.log(X);
    var p;
    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            p = (4 - i + j) % 4;
            console.log(p, X[4 * i + p]);
            X[4 * i + j] = S[4 * i + p];
        }
    }
    return S;
}
var A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
console.log(shiftRows(A));

1st phase is OK. But 2nd phase is weird, because by adding the statement to change X's element S is changing and also console output is also changing for previous line's X's element value!

1 Answers1

0

Objects (and therefore arrays, as arrays are objects), get copied by reference, so if you do:

 var X = S;

you copy a reference to the array stored in S to X, thus both are referencing the same array. To create a copy, do:

 var X = [...S];
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151