繁体   English   中英

我在理解此Javascript函数时遇到问题

[英]I'm having trouble understanding this Javascript function

我不了解toAlert变量在这里如何工作。 为什么要给它加上两个引号? 我也不了解for循环块中的“ toAlert”语句。 为什么toAlert = 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();
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";

您可以这样写。

var toAlert = "" ; 指示toAlert是string类型的变量

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

将字符串“ Lions,Tigers and 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();
    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"); 为该特定事件调用该自定义错误消息。
  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.

并且在代码中附加了圆括号。

您到底没有得到什么?

暂无
暂无

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

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