将值随机插入Javascript数组

将值随机插入Javascript数组,javascript,multidimensional-array,Javascript,Multidimensional Array,我使用8x8矩阵为游戏创建了一个表,我还将奖品等随机放置在表中,但我在为用户创建随机起始位置时遇到了一个问题,该位置与表中已有的对象不冲突 目前我有: function startPos(matrix) { var x = Math.round(Math.random() * matrix.length); var y = Math.round(Math.random() * matrix.length); while (matrix[y][x] != undefined) {

我使用8x8矩阵为游戏创建了一个表,我还将奖品等随机放置在表中,但我在为用户创建随机起始位置时遇到了一个问题,该位置与表中已有的对象不冲突

目前我有:

function startPos(matrix) {
  var x = Math.round(Math.random() * matrix.length);
  var y = Math.round(Math.random() * matrix.length);

  while (matrix[y][x] != undefined) {
    var x = Math.round(Math.random() * matrix.length);
    var y = Math.round(Math.random() * matrix.length);
    return matrix[y][x];
  };


  return matrix[y][x];
};
但我什么也得不到。抱歉,如果这个问题看起来很琐碎,我只是在启动Javascript,并且到处寻找相关的答案,但都没有结果

一些错误:

  • 您不能从循环中
    返回
    ,但必须检查条件才能离开循环
  • 您需要使用
    Math.floor
    而不是
    Math.round
  • 您需要返回位置,而不是字段的值(您刚才断言为
    未定义的


看起来您要做的是在矩阵中选择一个随机位置,如果它未定义,则返回它,否则选择一个新的随机位置并重试。您需要对此进行一些更改

First-循环中的return语句是不必要的,它会导致函数在循环的第一次运行时返回,从而停止它的工作

-在大多数情况下,您应该使用
==
==而不是
==
=。你可以在这里找到详细的解释-

Third-当您想检查变量是否未定义,而
myVar===undefined
应该在大部分时间都有效时,可能会出现失败的情况。最佳做法是使用myVar的类型==='undefined'
。更多信息请点击这里-

试试这个:

function startPos(matrix){
  // first select a random position
  var x = Math.round(Math.random() * matrix.length);
  var y = Math.round(Math.random() * matrix.length);

  // if the position is not empty, select a new one.
  // continue like this until an empty spot is found.
  while(typeof matrix[y][x] !== 'undefined'){
    x = Math.round(Math.random() * matrix.length);
    y = Math.round(Math.random() * matrix.length);
  };

  // once we have an empty position, return it
  return matrix[y][x];
};

警告-如果没有未定义的位置,循环将永远不会结束,因此您应该确保矩阵至少有一个空位,或者在函数开始时执行检查。

问题在于,您在
循环的第一次迭代中返回
。如果删除该
return
,则您的
while
循环将迭代,直到找到有效的
x
y
,然后循环将结束,您的代码将到达最后的
return
typeof…!==未定义的
始终为真“x和y的值从未更改[…]您正在创建仅存在于循环范围内的新变量”-否<代码>变量
具有函数作用域oops!用于将未定义的x==='undefined'
作为字符串放入
typeof x==='undefined'
。关于函数作用域,您是正确的。我已经编辑了我的答案以进行反思。
function startPos(matrix){
  // first select a random position
  var x = Math.round(Math.random() * matrix.length);
  var y = Math.round(Math.random() * matrix.length);

  // if the position is not empty, select a new one.
  // continue like this until an empty spot is found.
  while(typeof matrix[y][x] !== 'undefined'){
    x = Math.round(Math.random() * matrix.length);
    y = Math.round(Math.random() * matrix.length);
  };

  // once we have an empty position, return it
  return matrix[y][x];
};