Linnéa Andersson
Linnéa Andersson

Reputation: 41

My parameter becomes undefined, why is that?

I am trying to fill my grid with random positions by adding the grid positions to an array and then removing them with a random number as an index. The issue is that it randomly becomes undefined in the middle of my loop. It is the parameter of create_box that becomes undefined.

I'm trying to understand why it becomes undefined, the object gets sent to the function looking as it should. Somehow it doesnt work.

function go(n_columns,n_rows){
let array_of_cells=[];
let number_columns=n_columns+1;
let number_rows=n_rows+1;
for(let columns=1;columns<number_columns;columns++){
   
    for(let rows=1;rows<number_rows;rows++){
        let obj={column:columns, row:rows};
        array_of_cells.push(obj);
    }
}

while(1<array_of_cells.length){
    let random_number=Math.floor(Math.random() * array_of_cells.length-1)
    array_of_cells.splice(random_number,1);
    create_box(array_of_cells[random_number]);
    console.log(array_of_cells);
}

function create_box(position){
    console.log(position.row)
   let box=document.createElement("div");
   document.querySelector("#wrapper").appendChild(box);
   box.style.backgroundColor="red";
   box.style.gridArea = `${position.row} / ${position.column}`;
}

} go(10, 10);

Upvotes: 1

Views: 51

Answers (1)

humblots
humblots

Reputation: 93

I think that your issue comes from the fact that you are deleting a value (which reduces the number of indexes in your positions array), before accessing the position at "random_number" index that can sometimes be undefined.

You should probably use the spliced position instead.

while(array_of_cells.length) {
    const random_number = Math.floor(Math.random() * (array_of_cells.length - 1)) // note the use of parenthesis here
    const position = array_of_cells.splice(random_number, 1)[0];
    create_box(position);
    console.log(array_of_cells);
}

Upvotes: 2

Related Questions