How to get a local variabel to be set into a global one and use it in a secondary function? function 1 will be called in HTML initially then function 2 will be called...
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.