簡體   English   中英

Javascript 功能無法正常工作

[英]Javascript function is not working properly

我正在嘗試將此函數分配給此變量,但無論我嘗試什么都無濟於事,它給了我這個錯誤TypeError: addSix is not a function

 const createBase = num => {
      num + 6
    }
    
    let addSix = createBase(6);
    addSix(10); // returns 16
    addSix(21); // returns 27

請問有什么建議嗎?

要使addSize成為函數, createBase的返回值必須是函數。

createBase不返回任何內容 它沒有返回語句。 因此,它返回undefined

它甚至沒有創建返回的函數。

有幾個不同的問題:

  1. createBase是一個不返回任何內容的函數。

  2. 您嘗試創建為函數的部分 ( num => { num + 6 } ) 要么沒有{}要么應該有一個return ( more here )。

  3. 您正在對6硬編碼,但您應該使用傳遞給createBase的參數值。

您需要使createBase成為一個返回函數的函數:

 // `createdBase` vvvvvvvvvvvvvvvvvvvvvvvvvvv const createBase = num1 => num2 => num1 + num2; // The func it returns ^^^^^^^^^^^^^^^^^^^ let addSix = createBase(6); console.log(addSix(10)); // returns 16 console.log(addSix(21)); // returns 27

第一件事; num => { num + 6 } 如果您使用卷曲,則必須添加 return 語句。 否則,失去卷曲: num => num + 6 這將隱式添加一個 return 語句。

然后,如果您不習慣使用閉包,我建議您不要使用箭頭函數。

雖然這可能有效

const createBase = (num) => (num) => num + 6;
let addSix = createBase(6);
console.log(addSix(10));
console.log(addSix(21));

當你像這樣輸入它時,它對 javascript 初學者的作用要清楚得多;

const createBase = function(num) {
   return function (num) {
     return num + 6;
   }
};
let addSix = createBase(6);
console.log(addSix(10));
console.log(addSix(21));

您所擁有的是以下內容,如果寫出,則很明顯addSix被分配了 num+6 的值,而不是一個函數。

const createBase = function (num) {
    return num + 6
};

有兩個問題:

問題 1:

您需要使用 return 語句或刪除大括號:

const createBase = num => num + 6;

問題 2:

createBase(6)返回一個數字而不是一個函數。

因此,您不能將參數傳遞給數字。


例子:

const createBase = num => num + 6;
let addSix = createBase(6); // this is a number, not a function
addSix(21); // you can't call a number with arguments as function and hence the error

addSix是一個數字,您不能將參數傳遞給它並將其用作函數,因為它不是。

似乎您想創建一個返回單個參數函數的單參數功能,這可以像這樣實現。

const createBase = base => (num) => base + num;
let addSix = createBase(6);
addSix(10); // returns 16
addSix(21); // returns 27

另見:

  • 部分應用
  • 咖喱

(它們不太一樣: 柯里化和部分應用有什么區別?

暫無
暫無

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

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