在一个函数中使用全局声明的变量会阻止它在另一个函数中使用吗?

Does using a globally declared variable in one function stop it from being used in another?

我想了解为什么我的代码的一个版本有效而​​另一个版本无效。我已经在全局定义了 var 数字,所以我想如果我 运行 函数 sumArray() 那么它会传入元素,但它总是返回 0。只有当我再次将它定义为更接近函数 sumArray() 时,它计算正确。

是否使用 printReverse() 函数的变量编号禁止它在 sumArray() 中再次使用?如果您注释掉 var numbers = [2, 2, 3]; 那么您将在控制台中看到它 returns 0。

var numbers = [1, 2, 3];
var result = 0;

function printReverse() {
  var reversed = [];

  while (numbers.length) {
    //push the element that's removed/popped from the array into the reversed variable
    reversed.push(numbers.pop());
  }
  //stop the function 
  return reversed;
}
//print the results of the function printReverse()
console.log(printReverse());

var numbers = [2, 2, 3];

function sumArray() {
  //pass each element from the array into the function
  numbers.forEach(function(value) {
    //calculate the sum of var result + the value passed through and store the sum in var result
    result += value;
  });

  //return and print the sum
  return result;
}

//print the results of the function sumArray()
console.log(sumArray());

(当你注释掉var numbers = [2,2,3])

pop 方法修改了原始数组,因此当您到达 sumArray 函数时,您没有剩余的元素。

您可以使用 reverse 方法

numbers.reverse(); //this can completely replace the printReverse function