我似乎无法获得对象内部数组的长度

时间:2018-03-02 18:15:41

标签: javascript arrays object

我正在尝试创建一个刽子手游戏。我们的想法是拥有一个包含不同对象(谜题)的数组。从阵列中获取一个谜题并将其显示给用户。为了让用户看到破折号的数量,我试图通过array.puzzle进行循环,并使用破折号为数组中的每个索引创建一个新的变量。我似乎在for循环中有一个错误。我怀疑我可能以错误的方式调用长度。

console.log("Welcome to hangman type help(); for instructions!");
   
var cat = {
  puzzle: ["C", "A", "T"],
  category: "Animals",
  player: new Array(3)
}
    
var taylor = {
  puzzle: ["T", "A", "Y", "L", "O", "R", " ", "S", "W", "I", "F", "T"],
  category: "Singer",
  player: new Array(12)
}
    
taylor.player[6] = " ";
var puzzles = [cat, taylor];
//let quizz = puzzles[Math.floor(Math.random() * 2)];
    
function start() {
  var quiz = puzzles[Math.floor(Math.random() * 2)];
  var dashes = for (var i = 0; i =< (quiz.puzzle).length; i++) {
      if(quiz.puzzle[i] = " "){
          let guess = [];
          guess.push(" ");
      } else {
          guess.push(quiz[i]);
      }
      return guess;
  }             
  console.log("The category is " + quiz.category + ": " + dashes);
}

1 个答案:

答案 0 :(得分:0)

for()循环不返回值,因此使用赋值的右侧是不正确的。

卸下:

var dashes = and return guess;

移动:

let guess = [];就在for()循环之前。

此外:

小于或等于:<=而不是= <

console.log("Welcome to hangman type help(); for instructions!");

var cat = {
  puzzle: ["C", "A", "T"],
  category: "Animals",
  player: new Array(3)
}

var taylor = {
  puzzle: ["T", "A", "Y", "L", "O", "R", " ", "S", "W", "I", "F", "T"],
  category: "Singer",
  player: new Array(12)
}

taylor.player[6] = " ";

var puzzles = [cat, taylor];
//let quizz = puzzles[Math.floor(Math.random() * 2)];

function start() {
  var quiz = puzzles[Math.floor(Math.random() * 2)];
  let guess = [];

  for (var i = 0; i <= (quiz.puzzle).length; i++) {
    if (quiz.puzzle[i] = " ") {
      guess.push(" ");
    } else {
      guess.push(quiz[i]);
    }
  }

  console.log("The category is " + quiz.category + ": " + dashes);
}