Jump to content

add a row in a grid with push


espace
 Share

Recommended Posts

hi,

i make a grid with column and row and i want after add a new row below the last. how do you that ?

i make several test like this example below but that don't works....

 

var e=[];
for (var i = 0; i < 4; i++){
	e[i]=[]
	for (var x= 0; x < 4; x++){
		e[i][x]='tile';
	}
	
}

//result is 
//0: Array [ "tile", "tile", "tile",],
//1: Array [ "tile", "tile", "tile",],
//2: Array [ "tile", "tile", "tile",],
//3: Array [ "tile", "tile", "tile",],

//now i want to add a row a position 4 below position 3
for (var x= 0; x < 4; x++){
		e.push(e[4][x]='hole');
}

// expected result would be:
//0: Array [ "tile", "tile", "tile",],
//1: Array [ "tile", "tile", "tile",],
//2: Array [ "tile", "tile", "tile",],
//3: Array [ "tile", "tile", "tile",],
//4: Array [ "hole", "hole", "hole",],
//but don't work
	

 

Link to comment
Share on other sites

replace

for (var x= 0; x < 4; x++){
		e.push(e[4][x]='hole');
}

with

e.push(Array.from({length: 3}, () => 'hole'));

 

EDIT:

 

Whole code I would refactor

var e = Array.from({length: 4}, () => Array.from({length: 3}, (() => 'tile')));
console.log(e);
//0: Array [ "tile", "tile", "tile",],
//1: Array [ "tile", "tile", "tile",],
//2: Array [ "tile", "tile", "tile",],
//3: Array [ "tile", "tile", "tile",],

e.push(Array.from({length: 3}, () => 'hole'));
console.log(e);
//0: Array [ "tile", "tile", "tile",],
//1: Array [ "tile", "tile", "tile",],
//2: Array [ "tile", "tile", "tile",],
//3: Array [ "tile", "tile", "tile",],
//4: Array [ "hole", "hole", "hole",],

 

Check this out https://developer.mozilla.org/pl/docs/Web/JavaScript/Referencje/Obiekty/Array/from

 

And I recommend You to try this tutorial https://github.com/timoxley/functional-javascript-workshop

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...