我试图理解为什么我的代码的一个版本有效,而另一个版本不起作用。我已经全局定义了var数,所以我想如果我运行函数sumArray(),那么它会传入元素,但它总是返回0。只有当我再次定义它更接近函数sumArray()时,它才正确计算。将变量编号用于 printReverse() 函数是否会禁止在 sumArray() 中再次使用它?如果您注释掉,那么您将在控制台中看到它返回0。var numbers = [2, 2, 3];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());
添加回答
举报
0/150
提交
取消