我无法理解这个Javascript函数

时间:2014-01-06 07:18:28

标签: javascript

我不明白toAlert变量在这里是如何工作的。为什么分配两个引号?我也不理解for循环块中的“toAlert”语句。为什么要安排=去安息?

在搞乱了这个函数后,如果我要改变它,我想看看变量toAlert的效果。所以我把它分配给了

var toAlert;

并且它仅警告一行文本而不是5。任何人都可以向我解释这个吗?

var runAway = function(){
  var toAlert = "";
    for(var i = 0; i<5; i++){
      toAlert = toAlert + "Lions, Tigers, and Bears, Oh My!!\n";
    }
    alert(toAlert);
  }
}

runAway();

4 个答案:

答案 0 :(得分:1)

var toAlert = "";

这是一个空字符串。起初,toAlert变量只是一个空字符串。

toAlert = toAlert + "Lions, Tigers, and Bears, Oh My!!\n";

您将"Lions, Tigers, and Bears, Oh My!!\n"追加到toAlert变量的上一个值。

toAlert += "Lions, Tigers, and Bears, Oh My!!\n";

你可以这样写。

答案 1 :(得分:0)

var toAlert = "" ;表示toAlert是string

类型的变量

toAlert = toAlert + "Lions, Tigers, and Bears, Oh My!!\n";

将字符串“Lions,Tigers,Bears,Oh My !! \ n”连接到toAlert

的值

for循环内,

第一次,toAlert为空,因此在执行语句toAlert = toAlert + "Lions, Tigers, and Bears, Oh My!!\n";之后,toAlert的值将为

“”+“狮子,老虎和小熊,哦,我的!! \ n”

因为+在字符串的情况下表现得像一个连接运算符,它会连接两个'字符串'

第二次,它将是

“狮子,老虎和熊,哦,我的!! \ n”+“狮子,老虎和小熊,哦,我的!! \ n”

如果你需要将字符串附加5次,那么你的代码就是

var runAway = function(){
    var toAlert = "";
    for(var i = 0; i<5; i++)
    {
        toAlert = toAlert + "Lions, Tigers, and Bears, Oh My!!\n";
    }
    alert(toAlert);
}

runAway();

答案 2 :(得分:0)

    var runAway = function(){
    var toAlert = "";         // 1. this is just an empty string. Probably so that that they can customize it to how they want when they call alert(toAlert)
      for(var i = 0; i<5; i++){
        toAlert = toAlert + "Lions, Tigers, and Bears, Oh My!!\n";
      }
      alert(toAlert);
    }
    }

runAway();
  1. 例如,编码员可以拨打alert("This is error #424343 in div id #cats"); 如果发生错误,这将显示在警报中。 然后编码器有另一个警告/错误消息,如果div id #dogs中有错误,他想要显示。因此,他会键入alert("This is error whatever, in div id #dogs");来为该特定事件调用该自定义错误消息。

答案 3 :(得分:0)

  var runAway = function(){
   var toAlert = "";
   for(var i = 0; i<5; i++){
      toAlert = toAlert + "Lions, Tigers, and Bears, Oh My!!\n";
   }
   alert(toAlert);
  }


runAway is a function that has a variable named toAlert which is of string type, and then it iterates using for loop and concatenates the runAway string and adds "Lions, Tigers, and Bears, Oh My!!\n" on each iteration. After completion of iteration it alerts the complete string.

你的代码中有一个右括号。

你到底是怎么做到的?