【发布时间】:2015-11-06 11:10:26
【问题描述】:
我需要更新矩阵数组的帮助。它从设定值开始,我需要传入坐标来更新值。
我有一个基础矩阵:
var myMatrix = [
['-','-','-','-','-','-','-','-','-','-'],
['-','-','-','-','-','-','-','-','-','-'],
['-','-','-','-','-','-','-','-','-','-'],
['-','-','-','-','-','-','-','-','-','-'],
['-','-','-','-','-','-','-','-','-','-'],
['-','-','-','-','-','-','-','-','-','-'],
['-','-','-','-','-','-','-','-','-','-'],
['-','-','-','-','-','-','-','-','-','-'],
['-','-','-','-','-','-','-','-','-','-'],
['-','-','-','-','-','-','-','-','-','-']
];
我能够将矩阵中的特定点更新为如下所示:
----x-----
-----x----
--------x-
--------x-
---x------
----------
-------x--
----------
----x-----
-------x--
使用此功能:
function stepTwo(coordinates) {
console.log('Step Two');
for(var j =0; j < coordinates.length; j ++) {
myMatrix[coordinates[j].y][coordinates[j].x] = 'x';
}
for(var i = 0; i < myMatrix.length; i++) {
console.log(myMatrix[i].join(' '));
}
}
var coordinatesArray = [
{x: 4, y: 0},
{x: 5, y: 1},
{x: 8, y: 2},
{x: 8, y: 3},
{x: 3, y: 4},
{x: 7, y: 6},
{x: 4, y: 8},
{x: 7, y: 9},
];
stepTwo(coordinatesArray);
现在我想做另一个类似的函数,它应该像这样更新矩阵:
xxxxx-----
xxxxxx----
xxxxxxxxx-
xxxxxxxxx-
xxxx------
----------
xxxxxxxx--
----------
xxxxx-----
xxxxxxxx--
基本上传入行和多少个'-'转换成'x'。
我当前工作的 JS Fiddle(第三步是我需要帮助的地方): https://jsfiddle.net/2vbd27f0/73/
非常感谢您的帮助!
【问题讨论】:
-
提示:使用
Array.prototype.some或Array.prototype.map。这个功能很容易。看看你的小提琴:jsfiddle.net/2vbd27f0/74 -
请注意... stepTwo 没有更新数组。您将不得不返回结果。数组不是通过引用传递的。
-
@EmmanuelDelay First Google result。而且他甚至没有在任何地方传递数组。它是在全局范围内定义的,并且函数正在访问完全相同的变量(在范围内)。
标签: javascript arrays matrix