在 JavaScript 中创建一个网格数组



我想设置一个包含m * n对象的网格。此网格的宽度为 m 行和 n 列。

我先尝试了这段代码

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
}

显然,这是一个错误的语法。映射的初始化是错误的。如何创建可以通过将 x 和 y 坐标传递给数组来访问对象的数组?

假设我想访问 (3|7( 上的对象,我想去map[3][7] .

这可能吗?

您无法初始化 2d 数组,因为 js 中没有真正的 2d 数组。但是,您可以设置一个常规数组,并向其添加数组:

 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);

您的解决方案实际上并不遥远。不过,你是对的,你不能像let a = [][]那样初始化二维数组。如果只向 for 循环添加一行,则解决方案还会生成类似映射的结构:

在你的createMap()函数中,你只需要用数组初始化数组的每个字段,之后你可以填写这个数组的字段:

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); 
        }
    }
}

并将map初始化为一个简单的数组。

这是一个工作示例:

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);
}

您需要一个数组作为值,并检查一行是否不存在。

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);

使用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);

不确定您在创建网格或显示网格时是否遇到问题。

这是创建它的另一种方法:

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

以下是显示网格的 2 种方法:

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)));

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)];
}

此方法仅创建一个数学网格,您可以使用 pos() 函数引用该网格。

然后回答你的问题以获得 3,7 上的对象,你只需说

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

使用此方法时,1,1 是左上角,pos(1,1)将返回 0。

下面是一个不依赖于任何重新分配或突变的函数方法:

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);
    

colIndexrowIndex是可选的,它们不在此代码段中使用,但如果您需要根据元素在网格中的位置创建元素,它们是要使用的变量。

试试这个:

var x = new Array(10);
for (var i = 0; i < 10; i++) {
   x[i] = new Array(20);
}
x[5][12] = 3.0;

最新更新