尝试使用函数修改全局变量

问题描述

var age=25;

function modify(a) { 
  a=30; 
}

modify(age); 
console.log(age)

我希望修改age,它是将参数传递给我无法执行的函数全局变量。我仍在尝试学习JavaScript。预先感谢。

解决方法

如果是标量数据,则按值传递。因此,它不会更改年龄值。如果要更改它,则使用对象或数组。

,

将变量传递给函数时,该函数会创建一个局部变量,其作用域与该函数有关。该变量将永远不会指向您使用的实际变量。为了实现这一点,您需要将该函数的重新分配分配给变量。

在您的情况下,函数age中的全局变量a和局部变量modify指向不同的内存地址。因此,更新函数内部的局部变量将永远不会更新全局变量。

您可以通过多种方法来实现。您可以从该函数返回值,并将其分配给全局变量

var age=25;
function modify(a) {
  a = 30;
  return a;
}
age = modify(age);
console.log(age)

否则,您可以直接从函数中更新全局变量的值。在这种情况下,您将指向全局变量地址本身。

var age=25;
function modify(a) {
  age = 30;
}
modify(age);
console.log(age)

,
var age=25;

function modify(a) { return a=30 };

console.log(modify(age)); // logs 30

console.log(age); // still 25
,

您正在更新a

的值

如果要在函数内部更新年龄,则必须指向var age

age = 30

// declared var age and assign 25
var age = 25;

console.log("Initial value of age: ",age)

function modify(a) { 
  //here,within the function you have a variable 'a'
  console.log('value of a inside the function ',a)
  // you update the value of 'a' with 30
  // you never modify the value of age.
  a=30; 
  console.log("value of a after updating it: ",a)
  // because you declared age in the global scope you get access to it
  // to update age you must do
  age = 30
}

modify(age); 
console.log('final value of age: ',age)