0

Here is my code:

var arr = [];
var obj = {};

(function() {
  for(let i = 1; i <= 10; i++) {
    arr.push(i);
    obj[i] = arr;
  }
})();

This code gave me this output:

{
  '1': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ],
  '2': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ],
  '3': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ],
  '4': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ],
  '5': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ],
  '6': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ],
  '7': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ],
  '8': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ],
  '9': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ],
  '10': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 
}

Why doesn't it give an output like this?

{
  '1': [ 1 ], 
  '2': [ 1, 2 ], 
  '3': [ 1, 2, 3 ], 
  '4': [ 1, 2, 3, 4 ], 
  '5': [ 1, 2, 3, 4, 5 ], 
  '6': [ 1, 2, 3, 4, 5, 6 ], 
  '7': [ 1, 2, 3, 4, 5, 6, 7 ], 
  '8': [ 1, 2, 3, 4, 5, 6, 7, 8 ], 
  '9': [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ], 
  '10': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
}
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
AT808
  • 28
  • 5
  • 1
    This is because in JavaScript all programmatic objects are reference types. "arr" is a reference to an array and in your loop you assign this very same reference to each newly created member of your object "obj". So in fact, there is only one memory location (area) storing the elements of the array (1-10) and all members of "obj" (including "arr") point to that same memory location. – cli_hlt Aug 08 '17 at 20:13

1 Answers1

1

When you push, you're pushing the reference to the same array each time. What you actually want is to create a new array each time rather than reference the same one.

Check out this SO answer for more info Javascript by reference vs. by value

You could do this by pushing a copy arr using arr.slice or Array#from. At the very end arr will have all 10 numbers in it, but obj will look exactly like your output.

var arr = [];
var obj = {};

(function() {
  for(let i = 1; i <= 10; i++) {
    arr.push(i);
    obj[i] = arr.slice();
  }
  console.log(obj);
})();
Khauri
  • 3,753
  • 1
  • 11
  • 19