簡體   English   中英

為什么說 calcAverage 不是 function,而它是

[英]Why is it saying that calcAverage is not a function, when it is

我創建了一個簡單的 function 來計算 3 個數字的平均值:

let calcAverage = (v1,v2,v3) =>{

calcAverage = v1+v2+v3 / 3;

return calcAverage
}

const d1 = calcAverage(44, 23,71)
const k1 = calcAverage(44, 23,71)
console.log(d1)

如果你注釋掉: const k1 = calcAverage(44, 23,71)那么你會注意到const d1 = calcAverage(44, 23,71)有效,但為什么它說'Uncaught TypeError: calcAverage is not a function for這行代碼: const k1 = calcAverage(44, 23,71) ? 這對我來說沒有任何意義。 我如何使它們都起作用? 為什么它甚至說 calcAverage 不是 function 我首先?

因為您在這一行中重新分配calcAverage

calcAverage = v1+v2+v3 / 3;

這使得calcAverage成為一個number而不是 function

你為什么不立即返回這個計算

return v1+v2+v3 / 3;

第一次調用calcAverage時,它確實是一個 function。但是,您在 function 本身內將其覆蓋為一個number

calcAverage = v1+v2+v3 / 3;

只需更改 function 中的變量名稱即可使其按預期工作:

const calcAverage = (v1,v2,v3) =>{

    const result = v1+v2+v3 / 3; 

    return result;
}

const d1 = calcAverage(44, 23,71);
const k1 = calcAverage(44, 23,71);
console.log(d1);

更新:

要清楚地看到問題,您可以注銷每個 function 調用的calcAverage類型:

 let calcAverage = (v1,v2,v3) =>{ calcAverage = v1+v2+v3 / 3; return calcAverage; } console.log("Type before first call: ", typeof calcAverage); const d1 = calcAverage(44, 23,71); console.log("Type before second call: ", typeof calcAverage); const k1 = calcAverage(44, 23,71);

順便說一下,這很好地展示了使用const相對於使用let作為實際常量的優勢。 如果您將calcAverage聲明為const ,則不會遇到此問題。

我在 function 中發現了一個與 function 名稱相同的變量。 因此,當您第二次調用 calAverage 時,它不是 function,而是某種計算的結果。 我還把 function 作為常數

 const calcAverage = (v1, v2, v3) => { let calcAverageVal = v1 + v2 + v3 / 3 return calcAverageVal } const d1 = calcAverage(44, 23, 71) const k1 = calcAverage(44, 23, 71) console.log(d1)

此問題的解決方案是使用不同的變量名來保存 calcAverage 箭頭 function 內的計算值。

let calcAverage = (v1,v2,v3) =>{

   let calcValue = (v1+v2+v3) / 3;
   // it is recommended you bracket your numerator so as not to confuse the calcuation
   // because leaving it as v1+v2+v3 / 3 will solve the maths as v1+v2+(v3/3)

   return calcValue;
}

const d1 = calcAverage(44, 23,71);
const k1 = calcAverage(44, 23,71);
console.log(d1)

至於我,我確實建議你在聲明箭頭 function 時使用const 。它有助於使 function 不可操作

都是關於 scope 的依賴

  1. 第一次將calcAverage定義為 function
  2. 然后在這個 function 中你將這個元素重新定義為一個數字

=> 在第一次通話時:它是一個 function
=> 在第二次通話時:它不再是 function(它是一個數字)

您想隨時避免此類問題,您必須始終聲明所有變量

並且還建議初學者在嚴格模式下編寫代碼('use strict'; directive),這可以幫助你避免這種錯誤

示例代碼:

 'use strict'; // on first line, for all the code let calcAverage = (v1, v2, v3) => { let calcAverage = v1 + v2 + v3 / 3; // define a 'new' locale variable //╙╨╨─────────────────────────────────// within the scope of this function return calcAverage } const d1 = calcAverage(44, 23, 71) const k1 = calcAverage(40, 23, 71) console.log(d1) // 90.666... console.log(k1) // 86.666...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM