As the title says, the code is as follows:
var test = 0;
function fn(){
//...
fn2(test);//调用另一个方法,传入全局变量test
}
function fn2(t){
t++;//修改传入的变量,但是全局变量并没有受影响,这里的t不是一个指向全局test的路径吗?
}
Questions solved
欧阳克2017-06-28 09:28:51
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);
PHP中文网2017-06-28 09:28:51
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.
阿神2017-06-28 09:28:51
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.
滿天的星座2017-06-28 09:28:51
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();
巴扎黑2017-06-28 09:28:51
var test = 0;
function fn(){
test++;//这样就行了,这里的test操作的是全局变量 test
}
function fn2(t){
t++;//这样是不行的,因为这里t是局部变量,改变的是局部变量t的值,相当于 var t = test; t++;
}
習慣沉默2017-06-28 09:28:51
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] ++
}