As the title says, the code is as follows:
var test = 0;
function fn(){
//...
fn2(test);//調(diào)用另一個方法,傳入全局變量test
}
function fn2(t){
t++;//修改傳入的變量,但是全局變量并沒有受影響,這里的t不是一個指向全局test的路徑嗎?
}
Questions solved
The way you write it above just takes the value of test
as a parameter and passes it into fn2
. The parameter t
in fn2
is just the same as the value of test
.
If you want to modify external variables inside the function, you can write like this.
var test=3
function fn2(){
test++;
}
fn2();
console.log(test)
//也可以這樣寫
var test=3
function fn2(t){
return ++t;
}
test=fn2(test);
test=fn2(10);
The questioner has already answered "How to modify external variables"...
let test = 0;
function fn(){
test++;
}
fn(); // test == 1 這樣就行了
The parametert
certainly does not point to test
, because test
is a primitive type, and the primitive type is a value transfer method, which means that only a copy of the value is passed to the other party's variable; and the reference type is Reference (shared) transfer, the value of the reference type is the pointer to the object. When passing, a copy of this pointer is passed to the other party's variable. Modifying the other party's variable is modifying the original variable, because they point to the same memory address and the same an object.
let foo = { counter: 0};
function fn(){
fn2(foo);
}
function fn2(t){
t.counter++;
}
fn();// foo.counter == 1;//這樣就達到題主要的效果了
Reference (shared) passing can also be said to be a type of value passing, but the value passed is quite special, it is a pointer.
Javascript functions all pass by value instead of by reference. There is no relationship between t and test except that they have the same value.
Learn more about value passing and reference passing in js.
If you must write like this, you can encapsulate the test variable into an Object, and then pass the object to this function for modification.
var obj = {
test:0
}
function fn(){
fn2(obj);
}
function fn2(obj){
obj.test++;
}
fn();
var test = 0;
function fn(){
test++;//這樣就行了,這里的test操作的是全局變量 test
}
function fn2(t){
t++;//這樣是不行的,因為這里t是局部變量,改變的是局部變量t的值,相當于 var t = test; t++;
}
The basic types of JavaScript have no pointers and no references; Object says otherwise, so this is the only trick.
var global = {
test1: 1,
test2: 2
}
function fn () {
changeByPointer('test1')
}
function fn2() {
changeByPointer('test2')
}
function changeByPointer (pointer) {
// do something
global[pointer] ++
}