簡體   English   中英

如何在JavaScript中將箭頭函數(=>)的結果分配給變量

[英]How to assign a result of an arrow function (=>) to a variable in JavaScript

我試圖將箭頭函數結果分配給一個變量,如下所示:

function mutation(arr) {

  let allThere = true 

  while (allThere) {
    for (let c of arr[1]) {

      //the function in question below this line
      allThere = (c) => { 
        if (!arr[0].includes(c)) {
          return false
        }
      }
    }
  }

  return allThere;

因此,我希望發生的事情是從arrow函數返回一個布爾並將其存儲在allThere ,但實際上發生的是整個函數都存儲在該變量中,而不是函數的結果 我可能在這里缺少一些基本知識。

(作為附帶的問題,我想知道是否有一種方法可以使箭頭函數直接將值返回給外部函數mutations(arr) )。

在這種情況下,您必須使用IIFE(立即調用的函數表達式):

 function mutation(arr) { let allThere = true while (allThere) { for (let c of arr[1]) { //the function in question below this line allThere = ((c) => { if (!arr[0].includes(c)) { return false } })();//Immediately invoke the expression here to get the return value } } return allThere; } console.log(mutation([['1'], ['2']])); 

對於附帶的問題,您可以在調用IIFE之后返回:

 function mutation(arr) { let allThere = true while (allThere) { for (let c of arr[1]) { //the function in question below this line return ((c) => { if (!arr[0].includes(c)) { return false } })();//Immediately invoke the expression here to get the return value } } } console.log(mutation([['1'], ['2']])); 

所以我希望發生的是從箭頭函數返回一個布爾值並存儲在allThere

為此,您必須調用該函數。 同時定義和調用函數稱為IIFE(“內聯調用” [或“立即調用”]“函數表達式”):

    allThere = ((c) => { 
//             ^
      if (!arr[0].includes(c)) {
        return false
      }
    })()
//   ^^^

但請注意,您需要同時處理兩種情況(對與錯):

allThere = ((c) => { 
  return !arr[0].includes(c);
})()

...可以寫成簡潔的箭頭功能:

allThere = ((c) => !arr[0].includes(c))();

...但是,當然,根本不需要是一個函數:

allThere = !arr[0].includes(c);

(作為附帶的問題,我想知道是否有一種方法可以使箭頭函數直接將值返回給外部函數突變(arr))。

是的,因為該函數在顯示它的上下文中關閉了變量,所以您可以執行以下操作:

((c) => { 
  if (!arr[0].includes(c)) {
    allThere = false
  }
})()

...但是同樣,這里沒有理由要有功能。

您只是分配給不執行該功能的功能。 用這種方式看起來甚至沒用。 使用every

console.log(arr[1].every(c => arr[0].includes(c)));

暫無
暫無

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

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