【发布时间】: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