espace

add a row in a grid with push

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
	

 

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.