繁体   English   中英

在 JavaScript 上重复 function 5 次

[英]Repeat a function 5 times with for on JavaScript

我正在尝试使用不同的输入重复 function 5 次。 问题是,function 在 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")
}

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

这与变量i的 scope 有关。 由于您没有像这样声明变量: var i = 0let i = 0 ,因此 javascript 会将其视为全局变量。 这意味着 function 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") }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM