简体   繁体   English

在香草JavaScript的数组中创建具有xy坐标的对象矩阵

[英]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.

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