【问题标题】:Does using a globally declared variable in one function stop it from being used in another?在一个函数中使用全局声明的变量是否会阻止它在另一个函数中使用?
【发布时间】:2020-05-07 17:16:34
【问题描述】:

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

对 printReverse() 函数使用变量 numbers 是否会禁止它在 sumArray() 中再次使用?如果您注释掉 var numbers = [2, 2, 3];,您会看到它在控制台中返回 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());

【问题讨论】:

  • pop 修改原始数组,因此调用 printReverse 函数后您的数组不包含任何元素
  • 啊!我不知道 pop 永久更改了原始数组。我一定会记住这一点。谢谢!

标签: javascript function variables declaration variable-declaration


【解决方案1】:

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

pop 方法会修改原始数组,因此当您到达 sumArray 函数时,您将没有任何元素。

相反,您可以使用reverse 方法

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

【讨论】:

  • 我对使用 .reverse() 犹豫不决,因为我不确定它是否会产生我想要的结果。我改变了我的代码以便能够使用它,两种方法都产生相同的结果,但是 .reverse() 对于我的原始代码的总体目标来说肯定更好。谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-14
  • 1970-01-01
  • 2019-03-30
  • 1970-01-01
相关资源
最近更新 更多