【问题标题】:Printed string showing up as undefined打印的字符串显示为未定义
【发布时间】:2016-02-07 20:53:40
【问题描述】:

我正在尝试在函数内部创建一个 while 循环,该循环将打印出“我正在循环!”这句话。 3次。我遇到了困难,字符串打印未定义。虽然打印了三遍。我怎样才能得到字符串来打印我想要的短语?

我收到此错误Oops, try again. It looks like you're not printing the right string to the console.

var count = 0;
var loop = "I'm looping!";

var loop = function(){
    while(count < 3){
        console.log(loop(count++));
    }
};

loop();

我尝试将循环变量放入函数中。我还尝试将短语"I'm looping!" 放在循环()中,如下所示:

loop("I'm looping!");

我做错了什么?

【问题讨论】:

    标签: javascript function loops while-loop


    【解决方案1】:

    这里不需要函数: 你可以打印

    "I'm looping"
    

    3 次使用 just while。

    var count = 0;
    while(count < 3){
         console.log ("I'm looping") ;
         count++;
       }
    

    当前您正在打印未定义的循环函数的返回值,因为没有。

    【讨论】:

      【解决方案2】:

      您已将 both 命名为您的字符串和函数 loop。第二个声明替换你的loop 变量为一个函数;你的字符串不见了。

      您需要确保为每个变量命名不同的名称。您还需要检查您传递给console.log() 的内容。你想传递 string 以便打印出来。

      var count = 0;
      var loop_str = "I'm looping!";
      
      var loop = function(){
          while(count < 3){
              console.log(loop_str);
              count++;
          }
      };
      
      loop();
      

      【讨论】:

      • 谢谢!为什么我不能这样做呢? console.log(loop_str(count++));
      • @Paul:你希望loop_str(count++) 做什么? loop_str 是一个字符串,而不是一个函数。您为什么要尝试将count 传递给loop_str
      • 那么,这样做是在声明一个函数吗? loop_str(count++)
      • @Paul:不,这样做:function(){},是声明一个函数。执行loop(count++)调用一个函数。
      • @Paul: loop 是一个函数。你用loop(); 调用它。 loop_str 是一个字符串,它不是一个函数。你不能做loop_str()。调用函数时,可以将值作为参数传递给它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多