[英]How to use a variable within a function and use it in a secondary function? Javascript
How to get a local variabel to be set into a global one and use it in a secondary function?如何将局部变量设置为全局变量并在辅助 function 中使用它? function 1 will be called in HTML initially then function 2 will be called... function 1 最初将在 HTML 中调用,然后 function 2 将被调用...
function test1(){ var test1 = 1; } function test2(){ var test2 = test1 + 3; }
In order to use the variable "test1" within the "test2" function, you can either pass it as an argument to the "test2" function, or you can make the "test1" variable a global variable by declaring it outside of the "test1" function. Here's an example of both methods:为了在“test2”function 中使用变量“test1”,您可以将其作为参数传递给“test2”function,或者您可以通过在“test1”外部声明它来使“test1”变量成为全局变量test1" function。下面是这两种方法的示例:
Method 1: Pass as an argument方法一:作为参数传递
function test1(){
var test1 = 1;
test2(test1);
}
function test2(test1){
var test2 = test1 + 3;
console.log(test2);
}
Method 2: Declare as a global variable方法二:声明为全局变量
var test1;
function test1(){
test1 = 1;
}
function test2(){
var test2 = test1 + 3;
console.log(test2);
}
In both cases, calling the function test1() will set test1 = 1 and test2() will use that value and print 4 to the console.在这两种情况下,调用 function test1() 将设置 test1 = 1,test2() 将使用该值并将 4 打印到控制台。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.