在 JavaScript 上使用 for 重复函数 5 次

San*_*oza 1 javascript loops for-loop function

我试图用不同的输入重复一个函数 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")
}
Run Code Online (Sandbox Code Playgroud)

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

use*_*661 5

这与变量的作用域有关i。由于您没有像这样声明变量:var i = 0or let i = 0,javascript 会将其视为全局变量。这意味着i函数commandos中的变量i与外部 for 循环中的变量相同。所以循环 incomandos会增加 的值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")
}
Run Code Online (Sandbox Code Playgroud)