-4

They both contain the same values, but I'm wondering why they look different when I console them out in Dev tools.

enter image description here

var values = [6, 6, 6, 19, 13, 50]; 

function boxWidth() {
    var widths = new Array();
    widths.push(values);
    console.log(widths);
    console.log(values);
} 
Edgar Quintero
  • 4,223
  • 2
  • 34
  • 37
  • To clarify, you're asking why `widths` is `[Array(6)]` but `values` is `[6,6,6,19,13,50]`? – Dai Aug 31 '17 at 21:12
  • "*They both contain the same values*" - well no, they don't. Click the inspect button (grey triangle) to see how they differ. – Bergi Aug 31 '17 at 21:15
  • To clarify. one looks like -> `[6,6,6,19,13,50]` and the other looks like `[[6,6,6,19,13,50]]` if that help you see the difference.. – Keith Aug 31 '17 at 21:16
  • thats obviously a nested array read more about stacks in JS – Abr001am Sep 01 '17 at 09:32

2 Answers2

5

The widths array is an array that has a single member referencing the values array, whereas values is an array of 6 numbers.

To copy the numbers in individually, do this:

widths.push(...values);

Or do it when you create the array:

var widths = [...values];

Or to be legacy compatible:

var widths = values.slice();

You can serialize the arrays to get a clearer view.

var values = [6, 6, 6, 19, 13, 50]; 

function boxWidth() {
    var widths = new Array();
    widths.push(values);
    console.log(JSON.stringify(widths));
    console.log(JSON.stringify(values));
} 

boxWidth();
spanky
  • 2,768
  • 8
  • 9
4

values is a 1-dimensional array containing 6 numbers.

widths is a 2-dimensional array. Its first dimension is a single element, which is a reference to values. The second dimension is the 6 numbers in values.

console.log() only displays the first dimension in detail by default. You can click on the disclosure triangle of widths to see the contents of the inner dimension. If you change it to log JSON, you'll see the full structure of each. Then you'll see the extra level of nesting in widths.

var values = [6, 6, 6, 19, 13, 50]; 

function boxWidth() {
    var widths = new Array();
    widths.push(values);
    console.log(JSON.stringify(widths));
    console.log(JSON.stringify(values));
} 

boxWidth();
Barmar
  • 741,623
  • 53
  • 500
  • 612