【问题标题】:Repeat a function 5 times with for on JavaScript在 JavaScript 上使用 for 重复一个函数 5 次
【发布时间】:2020-05-16 22:21:17
【问题描述】:

我正在尝试使用不同的输入重复一个函数 5 次。问题是,该函数在 for 循环之外可以正常工作,但在其中只能工作 1 次。 这是我的代码:

    var string;
var num;
function comandos(string, num){

    let resultado = "";

    for (i=0; i<string.length; i++){

        if (string.charAt(i) == "i"){
            num = num + 1;
        }else if (string.charAt(i) == "d"){
            num = num - 1;
        }else if (string.charAt(i) == "c"){
            num = Math.pow(num, 2);
        }else if (string.charAt(i) == "p"){
            resultado = resultado + "*" + num + "*";
        }
    }

return resultado;

}

for (i=0; i<5; i++){
    string = prompt("Ingrese secuencia de comandos (i, d, c, p)").toLowerCase();
    num = parseInt(prompt("Ingrese número"));
    console.log(comandos(string, num));
    console.log("prueba")
}

编辑:我刚刚意识到我有很多关于西班牙语的代码,如果你们需要翻译,请告诉我。

【问题讨论】:

  • 当你说它只会运行一次时,你的意思是它运行了五次但每次都给出相同的结果还是循环只运行一次?
  • 循环只运行一次,两个提示都只提示一次,函数只运行一次。 las console.log("prueba") 是一个测试,它只运行一次,但如果我删除它上面的所有其余代码,它确实会运行 5 次。
  • 让 i=0 代替 i=0
  • 明白了。 comandos 的字符串参数是否曾经超过一个字符?
  • 当然——只是认为你可以完全消除 for 循环 :)

标签: javascript function loops for-loop


【解决方案1】:

这与变量i 的范围有关。由于您没有像这样声明变量:var i = 0 或 let i = 0,javascript 会将其视为全局变量。这意味着函数 commandos 中的 i 与外部 for 循环中的 i 变量相同。所以comandos中的循环会增加i的值,导致外层for循环提前退出。

var string;
var num;

function comandos(string, num) {

  let resultado = "";

  for (let i = 0; i < string.length; i++) {

    if (string.charAt(i) == "i") {
      num = num + 1;
    } else if (string.charAt(i) == "d") {
      num = num - 1;
    } else if (string.charAt(i) == "c") {
      num = Math.pow(num, 2);
    } else if (string.charAt(i) == "p") {
      resultado = resultado + "*" + num + "*";
    }
  }

  return resultado;

}

for (let i = 0; i < 5; i++) {
  string = prompt("Ingrese secuencia de comandos (i, d, c, p)").toLowerCase();
  num = parseInt(prompt("Ingrese número"));
  console.log(comandos(string, num));
  console.log("prueba")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 2018-10-28
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    相关资源
    最近更新 更多