【问题标题】:JS: Assignment within if statment doesn't workJS:if 语句中的赋值不起作用
【发布时间】:2015-10-12 13:23:02
【问题描述】:

我有一个二维数组,想将随机元素值设置为 2。 我的尝试如下,但没有奏效.. 如果随机值未定义,则将其设置为 2,如果不重复。 提前致谢!

var randomTileFunction = function (board) {
  var randomTile = board[Math.floor(Math.random() * 4)][Math.floor(Math.random() * 4)];
  if(randomTile === undefined) {
    randomTile = 2;
  } else {
    randomTileFunction(board);
  }
};

【问题讨论】:

  • “但这不起作用” - 会发生什么?
  • 我之后记录了数组,它保持不变。 Webstorm 在第 4 行说:“分配的值从未使用过”

标签: javascript arrays function random variable-assignment


【解决方案1】:

randomTile 是一个变量,其赋值不会影响另一个变量board[Math.floor(Math.random() * 4)][Math.floor(Math.random() * 4)]

var i = Math.floor(Math.random() * 4);
var j = Math.floor(Math.random() * 4);
if(board[i][j] === undefined) {
  board[i][j] = 2;

【讨论】:

  • 谢谢,成功了!顺便说一句:再次调用函数是一种好习惯吗?
  • 这是正常的做法,如果你的逻辑需要递归
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-24
  • 2016-09-07
  • 1970-01-01
  • 2011-10-30
  • 2011-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多