[英]create a matrix of objects with x y coordinates within arrays in vanilla JavaScript
I'm trying to create a matrix of objects with x, y coordinates. 我正在尝试创建具有x,y坐标的对象矩阵。
For example: 例如:
var simpleMatrix = [ [{x: 0, y: 0}, {x: 0, y: 1}], [{x: 1, y: 0}, {x: 1, y: 1}], ] console.log('simpleMatrix is: ', simpleMatrix)
How do I abstract this into a function so I can generate a bigger grid? 如何将其抽象为函数,以便生成更大的网格? For example, a grid with 10 rows by 10 columns (or 5 rows by 6 columns, or whatever).
例如,一个具有10行乘10列(或5行乘6列,或其他)的网格。
I want an array of objects that each contain their own coordinates. 我想要一个对象数组,每个对象包含自己的坐标。
You can chain two Array.from
s together to build nested arrays from scratch: 您可以将两个
Array.from
在一起,以从头开始构建嵌套数组:
const makeMatrix = (lengthX, lengthY) => ( Array.from( { length: lengthY }, (_, y) => Array.from( { length: lengthX }, (_, x) => ({ x, y }) ) ) ); console.log(makeMatrix(2, 2)); console.log(makeMatrix(3, 1));
The first argument to Array.from
is an object that the interpreter attempts to turn into an array. Array.from
的第一个参数是解释器尝试转换为数组的对象。 Passing an object with a length
property will create an array of that length with undefined
values. 传递具有
length
属性的对象将创建具有undefined
值的该长度的数组。 Then, the second argument to Array.from
is an optional mapping function, the same as Array.prototype.map
- here, we can exploit that by using the second argument to .map
, which is the current index being iterated over. 然后,
Array.from
的第二个参数是一个可选的映射函数,与Array.prototype.map
相同-在这里,我们可以通过使用.map
的第二个参数来利用它,这是正在迭代的当前索引。
So, with the outer Array.from
's getting the y
coordinate from the mapper, and the inner Array.from
getting the x
coordinate from the mapper, we can then return an object with the desired coordinates from the inner function, which will create the grid. 因此,通过外部
Array.from
从映射器获取y
坐标,内部Array.from
从映射器获取x
坐标,我们可以从内部函数返回具有所需坐标的对象,这将创建网格。
var inputCoord = [];
var matrix;
function initMatrix( rows, cols ) {
var index = 0;
var aMatrix = [];
for( var x = 0; x < rows; x++ ) {
var aRow = [];
for( var y = index; y < inputCoord.length; y++ ) {
aCol.push( inputCoord[ y ] );
if( y == ( cols - 1 ) ) {
index += cols;
break;
}
}
aMatrix.push( aRow );
}
return aMatrix;
}
inputCoord.push( { x: 0, y: 1 } );
inputCoord.push( { x: 0, y: 1 } );
inputCoord.push( { x: 0, y: 1 } );
inputCoord.push( { x: 0, y: 1 } );
inputCoord.push( { x: 0, y: 1 } );
inputCoord.push( { x: 0, y: 1 } );
matrix = initMatrix( 2, 3 ); //rows * cols have to always be equal to inputCoord.length
I didn't try the code, but something like this should work. 我没有尝试该代码,但是类似的东西应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.