我試圖理解為什么我的代碼的一個(gè)版本有效,而另一個(gè)版本不起作用。我已經(jīng)全局定義了var數(shù),所以我想如果我運(yùn)行函數(shù)sumArray(),那么它會(huì)傳入元素,但它總是返回0。只有當(dāng)我再次定義它更接近函數(shù)sumArray()時(shí),它才正確計(jì)算。將變量編號(hào)用于 printReverse() 函數(shù)是否會(huì)禁止在 sumArray() 中再次使用它?如果您注釋掉,那么您將在控制臺(tái)中看到它返回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());
在一個(gè)函數(shù)中使用全局聲明的變量是否會(huì)阻止在另一個(gè)函數(shù)中使用該變量?
慕姐4208626
2022-08-04 16:48:47