在javascript中更改文字函数中变量的值

时间:2014-03-29 14:58:14

标签: javascript function variables

我想知道如何得到这个结果:

function() {
   var myVar = "";
   function () {
      myVar += "This is ";
   }
   myVar = "my string";
   alert(myVar); //would like it to display: This is my string
   // only displays: my string
}

2 个答案:

答案 0 :(得分:3)

你必须调用一个函数才能执行它,B必须重新组织你的字符串

function() {
   var myVar = "";
   function update() {
      myVar = "This is " + myVar;
   }
   myVar = "my string";
   update();
   alert(myVar); //would like it to display: This is my string
   // only displays: my string
}

答案 1 :(得分:1)

您必须调用该功能。

var myVar = "";
function someFunction() { // Give it a name
   myVar += "This is ";
}
myVar = "my string";
someFunction(); // and call it
alert(myVar);