Q
Q
qo_0p2015-10-04 16:14:51
JavaScript
qo_0p, 2015-10-04 16:14:51

Fibbonacci array cycle or unpredictable WTF array behavior?

Everything is fine with this build.

var a = [];
var b = [];
var c = [];

a[0] = 1;
b[0] = 1;
for (var i = 0; i < 4; ++i) {
  c = a;
  console.log(c);   // выводит [1] Ок!
  a[0] = a[0] + b[0];
  b = c;
  console.log(c);   // выводит [1] Ок!
}

But if we add a loop, something strange happens!
var a = [];
var b = [];
var c = [];

a[0] = 1;
b[0] = 1;
for (var i = 0; i < 4; ++i) {
  c = a;
  console.log(c);   // выводит [1] Ок!
  for (var j = 0; j < a.length; ++j) {
    a[j] = a[j] + b[j];
  }
  b = c;
  console.log(c);   // выводит [2] ПОЧЕМУ????
}

Please help me figure out why this is happening?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Inchin ☢, 2015-10-04
@In4in

Code parsing
var a = []; 
var b = [];
var c = [];

a[0] = 1;
b[0] = 1;

for (var i = 0; i < 4; ++i) {
  c = a; 
  for (var j = 0; j < a.length; ++j) {
    a[j] = a[j] + b[j]; //a[j] = c[j] = a[j] + b[j];
  }
  b = c; //b = c = a
  console.log(c);   // выводит [2], потому что c[0] = a[0] = b[0] + a[0] = 1 + 1 = 2
}

Complex types, unlike simple ones, are passed by reference.
var a = "text", b = a;
b = "Other text"; 
console.log(a, b); //text, Other text

var arr = [], brr = arr;
arr.push("item");
console.log(a[0], b[0]); //item, item

To copy an array while creating a new object, use array.slice().
In general, here is the solution to your problem.
By the way, an interesting note about him:
bd7220a135594186a8783be01ad46b21.PNG

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question