I
I
Ivan Bogomolov2014-10-19 18:11:19
JavaScript
Ivan Bogomolov, 2014-10-19 18:11:19

Javascript array bug or am I dumb?

function getArray(size) {
var ar = [];
    for(var i = 0 ; i < size;i++)
    {
      var inGrid = new Array(size);
      for(var n = 0 ; n < size; n++) {
        inGrid.push("grid_" + n);
      }
      ar.push(inGrid);
    }
    return ar;
}
var result = getArray(12);
alert(result[0].length); //24

There are 12 elements inside result[0] and length shows 24.
Is this correct behavior or am I missing something.
Tell me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Zhak, 2014-10-19
@kraso4niy

In general, you can see what is stored in this array:

console.log( result[0] ); 
// [undefined × 12, "grid_0", "grid_1", "grid_2", "grid_3", "grid_4", "grid_5", "grid_6", "grid_7", "grid_8", "grid_9", "grid_10", "grid_11"]

Although it is obvious here - you first fill the array with twelve undefined elements, and then add 12 to the end of the array. The result is 24.
/* Редкий синтаксис: аргумент new Array - одно число.
При этом создается массив заданной длины, 
все значения в котором undefined */
var array = new Array(10)

Source

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question