Alter outer argument var of node.js

Please look at these 3 code blocks first.

Code Block 1:

var t1 = function(aaa) {
        setTimeout(function(){
        a = 'bb';
        aaa.push(a);
    }, 1000);

}

var t3 = function() {
    var aa = new Array;
    aa[0] = 'aa';

    console.log(aa);
    t1(aa);

    setTimeout(function(){
        console.log(aa);
    }, 3000);
}

t3();

Output:[ ‘aa’ ] [ ‘aa’, ‘bb’ ]

Code Block 2:

var t1 = function(aaa) {
        setTimeout(function(){
        aaa[1] = 'bb';
    }, 1000);

}

var t3 = function() {
    var aa = new Array;
    aa[0] = 'aa';

    console.log(aa);
    t1(aa);

    setTimeout(function(){
        console.log(aa);
    }, 3000);
}

t3();

Output:[ ‘aa’ ] [ ‘aa’, ‘bb’ ]

Code Block 3:

var t1 = function(aaa) {
        setTimeout(function(){
        aaa = aaa.concat('bb');
    }, 1000);

}

var t3 = function() {
    var aa = new Array;
    aa[0] = 'aa';

    console.log(aa);
    t1(aa);

    setTimeout(function(){
        console.log(aa);
    }, 3000);
}

t3();

Output:[ ‘aa’ ] [ ‘aa’ ]

The problem is code block 3 that the ‘concat’ method can’t modify the ‘aaa’ var pass by argument.

What’s the difference of ‘concat’ ,’push’ and direct modify?

Problem courtesy of: Magic

Solution

In codeblock 1 and 2, you are modifying the contents of aa
.

While in codeblock 3 you are rebinding
aaa
to another array, and the aaa
in function t1
is not a reference to the outside aa
anymore. So the outside aa
is not being modified.

you can refer to Is JavaScript a pass-by-reference or pass-by-value language?
to see the detailed explanation on Javascript’s variable passing behavior.

Solution courtesy of: qiao

Node.js Recipes责编内容来自:Node.js Recipes (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Alter outer argument var of node.js

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录