亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

javascript - How to modify an external variable inside a function
給我你的懷抱
給我你的懷抱 2017-06-28 09:26:51
0
7
1126

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

給我你的懷抱
給我你的懷抱

reply all(7)
學霸

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.

扔個三星炸死你

Just change it directly, no need to pass in the 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] ++
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template