天天看点

函数的参数传递是通过值还是引用

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,标量基本类型是不可更改的(字符串和布尔也是)。即使这里是数字对象