首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在JavaScript上使用for重复一个函数5次

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

Stack Overflow用户
提问于 2020-05-17 06:21:18
回答 1查看 154关注 0票数 1

我尝试用不同的输入将一个函数重复5次。问题是,该函数在for循环之外工作正常,但在循环内部它只能工作一次。下面是我的代码:

代码语言:javascript
复制
    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")
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-17 06:27:43

这与变量i的作用域有关。因为你没有像这样声明变量:var i = 0let i = 0,javascript会把它当作一个全局变量。这意味着函数commandos中的i与外部for循环中的i是相同的变量。因此,comandos中的循环将增加i的值,从而导致外部for循环提前退出。

代码语言:javascript
复制
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")
}

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61844366

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档