简体   繁体   中英

create a grid array in JavaScript

I want to setup a grid containing m * n objects. This grid got a width of m rows and n columns.

I tried this code first

let map = [][]; // Create an array that takes a x and y index

function createMap() {
    for (let x = 0; x < columnCount; x++) {
        for (let y = 0; y < rowCount; y++) {
            addCell(x, y); 
        }
    }
}

function addCell(x, y) {
    map[x][y] = cell(); // create a new object on x and y
}

Obviously this is a wrong syntax. The initialization of map is wrong. How can I create the array that I can access a object by passing in the x and y coordinate to the array?

Let's say I want to access the object on (3|7) I want to go for map[3][7] .

Is that possible?

You cant initialize a 2d array, as there are no real 2d arrays in js. However you could setup a regular array, and add arrays to it:

 function createMap(columnCount, rowCount) {
   const map = [];
   for (let x = 0; x < columnCount; x++) {
     map[x] = []; // set up inner array
     for (let y = 0; y < rowCount; y++) {
        addCell(map, x, y);
     }
   }
   return map;
 }

 function addCell(map, x, y) {
    map[x][y] = cell(); // create a new object on x and y
 }

 const map = createMap(10, 10);

You need a single array as value and a check if one row does not exist.

 function createMap(rowCount, columnCount) { for (let x = 0; x < rowCount; x++) { for (let y = 0; y < columnCount; y++) { addCell(x, y); } } } function addCell(x, y) { map[x] = map[x] || []; map[x][y] = x + '|' + y; } var map = []; createMap(4, 8); console.log(map[3][7]); console.log(map); 

An approach by using Array.from .

 function createMap(rowCount, columnCount) { map = Array.from( { length: rowCount }, // take rowCount as length (_, i) => Array.from( // fill with new array { length: columnCount }, // take columnCount for every row (_, j) => [i, j].join('|') // initialize cell with some value ) ); } var map; createMap(4, 8); console.log(map[3][7]); console.log(map); 

You aren't actually that far off with your solution. You're right, though, you cannot initialize a two-dimensional array like let a = [][] . If you add just one line to your for-loops, your solution also produces a map-like structure:

In your createMap() function, you just need to initialize every field of the the array with an array, after that you can fill the fields of this array:

function createMap() {
    for (let x = 0; x < 10; x++) {
        map[x] = []; // initialize map[x] as an array
        for (let y = 0; y < 10; y++) {
            addCell(x, y); 
        }
    }
}

And initialize map as a simple array.

Here is a working example:

 let map = []; createMap(); console.log(map); function createMap() { for (let x = 0; x < 5; x++) { map[x] = []; for (let y = 0; y < 5; y++) { addCell(x, y); } } } function addCell(x, y) { map[x][y] = cell(x,y); // create a new object on x and y } function cell(x,y) { return (x+1)+":"+(y+1); } 

Not sure if you are having trouble creating the grid or displaying it.

Here is yet another way to create it:

const grid = Array.from(new Array(5),(_,x)=>Array.from(new Array(5),(_,y)=>addCell(x,y)));

Here are 2 ways to show the grid:

 const grid = Array.from(new Array(5),()=>Array.from(new Array(5),()=>"-")); const rotate = grid => grid[0].map( (_,y)=>grid.map( (_,x)=>[y,x] ) ).map( row=>row.map(([x,y])=>grid[y][x]) ); const format = grid => grid.map(x=>x.join(" ")).join("\\n"); //set some values of grid [[0,2],[1,2],[2,2],[3,2],[4,2]].forEach( ([x,y])=>grid[x][y]="X" ); //you can map the grid to columns first, it'll look like it's rotated // unless you generate the columns in div float lefts console.log("map grid columns first:") console.log(format(grid)); //you can rotate the grid to build each row and then each column like html table console.log("map grid rows first:") console.log(format(rotate(grid))); 

Here's a functional method that doesn't rely on any reassignment or mutation:

 const lengthX = 5; const lengthY = 2; const map = Array.from({ length: lengthX }, (_, colIndex) => ( Array.from({ length: lengthY }, (_, rowIndex) => ( // some element to put in each, for example { foo: 'bar'} )) )); console.log(map); 

The colIndex and rowIndex are optional, they're not used in this snippet, but if you need to create elements based on their location in the grid, they're the variables to use.

try this:

var x = new Array(10);
for (var i = 0; i < 10; i++) {
   x[i] = new Array(20);
}
x[5][12] = 3.0;
var grid=[];
var grid_length=10; //mathematical length
var grid_width=10;  //mathematical width

function pos(x,y){
  return (y*grid_length)-grid_length-1+x-2;
}

function replaceItem(x,y,item){
  grid[pos(x,y)]=item;
}

var itemsRequested=[];
function iRequest(x,y){ // get Item on grid.
  itemsRequested.push(grid[pos(x,y)]);  // this both adds the Object to a list and returns it
  return grid[pos(x,y)];
}

This method only makes a mathematical grid, with which you can reference with the pos() function.

Then to answer your question to get the object on 3,7 you would simply say

var a=iRequest(3,7);
//currently would return undefined because there are no objects in the array.

When using this method, 1,1 is the top left corner, and pos(1,1) would return 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM