0

I have created a variable of type multidimensional array in JavaScript and I console it before sending to function but it displays wrong output at console, but if i remove the function all works great

function ROT(a, d) {
    return a ^ d;
}

function thetha_step(A) {

    const C = [];
    const D = []; 
    //C[x] part 
    for (let x=0; x<5; x++) {
         C[x] = A[x][0];
         for (let y=1; y<5; y++) {
            C[x] = C[x] ^ A[x][y];
         }
    }

    //D[x] part
    D[0] = C[4] ^ ROT(C[1], 1);
    for (let x=1; x<5; x++) {
       D[x] = C[x-1] ^ ROT(C[x+1], 1);
    }

    //A[x,y]
    for (let x=0; x<5; x++) {
         for (let y=0; y<5; y++) {
             A[x][y] = A[x][y] ^ D[x];
         }
    }

    return A;
}


var bin= [
    [1, 0, 0, 0, 1],
    [0, 1, 0, 0, 0],
    [0, 0, 1, 1, 1],
    [1, 0, 1, 1, 1],
    [1, 0, 1, 0, 1]
];


console.log(bin);

console.log(thetha_step(bin));
# Outputs as #

(5) [Array(5), Array(5), Array(5), Array(5), Array(5)]
0: (5) [2, 3, 3, 3, 2]
1: (5) [2, 3, 2, 2, 2]
2: (5) [1, 1, 0, 0, 0]
3: (5) [2, 3, 2, 2, 2]
4: (5) [1, 0, 1, 0, 1]

(5) [Array(5), Array(5), Array(5), Array(5), Array(5)]
0: (5) [2, 3, 3, 3, 2]
1: (5) [2, 3, 2, 2, 2]
2: (5) [1, 1, 0, 0, 0]
3: (5) [2, 3, 2, 2, 2]
4: (5) [1, 0, 1, 0, 1]

Im not understanding why its not displaying correct bin variable values, but when I remove the function then all displays correct. Please help me where Im going wrong.

  • maybe you witness an asynchron output of the console of chrome: https://stackoverflow.com/questions/23392111/console-log-async-or-sync – Nina Scholz Oct 07 '19 at 21:27
  • You'll want to look at [weird array behaviour in javascript](https://stackoverflow.com/q/49838597/215552), and [Why does changing an Array in JavaScript affect copies of the array?](https://stackoverflow.com/q/6612385/215552) – Heretic Monkey Oct 07 '19 at 21:51

1 Answers1

0

There are two things combining here.

First, arrays are objects and are thus passed "by reference". When you modify A inside the function, you're actually modifying the same array that is in bin, not a copy of it.

Second, the browser console displays "live" objects - when the contents of an object change, the console display changes too.

If you want to capture the value of bin as it was when you outputted it, try doing this instead:

console.log(JSON.stringify(bin));
Vilx-
  • 104,512
  • 87
  • 279
  • 422