首页 > 解决方案 > 如何在 Javascript 中将数字添加到变量中?

问题描述

我需要通过这个程序猜测 4 位代码,但我不知道为什么它不起作用。
我尝试使用两个 for 循环来猜测从 0 到 9 的所有数字的 4 位数字。
但是,该程序不打印任何内容。
我想知道如何将当前值添加x到变量result中。

function start() {
  var secretPasscode = generateRandomPasscode();

  // Write your code here
  var result = "";
  //Loop through for the secretPasscode's length
  for(var i = 0; i < secretPasscode.length; i++){
      
    //Put numbers from 0 to 9
    for(var x = 0; x < 10; x++){
      result = "";
      var currNum = x;
      //If the current number is right, store it to the result
      if(currNum == secretPasscode.charAt(i)){
        result += x;
      }else{
        result = result;
      }
    }
  }
  return result;
  println(result);
}

function isCorrect(guessCode, correctCode) {
  return guessCode == correctCode;
}

// Generates a random 4 digit passcode and returns it as a String
function generateRandomPasscode() {
  var randomPasscode = "";
  
  for(var i = 0; i < 4; i++) {
    var randomDigit = Randomizer.nextInt(0, 9);
    randomPasscode += randomDigit;
  }
  return randomPasscode;
}

标签: javascriptfor-loop

解决方案


推荐阅读