【发布时间】: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