天天看點

函數的參數傳遞是通過值還是引用

1. function test( x){ x. push( 5); console. log( x); //[1,2,3,5] } var array = [ 1, 2, 3]; test( array); console. log( array); //[1,2,3,5]這裡是引用了同一個對象,是以值同步 2. function test( x){ x. push( 5); //這裡x和array都是[1,2,3,5] x = [ 6, 6, 6] console. log( x); //[6,6,6]因為x被強制指派為另一個數組,是以與之前對象的指針斷裂,由此值改變 } var array = [ 1, 2, 3]; test( array); console. log( array); //[1,2,3,5]雖然x被指派,但是不會影響array原本的指向

3.function test( x) { x++; console. log( 'hi' + x); //x=3 } var a = 2; var b = new Number( a); test( b); console. log( b); //值是2,标量基本類型是不可更改的(字元串和布爾也是)。即使這裡是數字對象

function test( x) { x++; console. log( 'hi' + x); //x=3 } var a = 2; var b = new Number( a); test( b); console. log( b); //值是2,标量基本類型是不可更改的(字元串和布爾也是)。即使這裡是數字對象