如何将箭头函数 (=>) 的结果分配给 JavaScript 中的变量

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

我正在尝试将箭头函数 result 赋值给一个变量,如下所示:

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;

所以我希望发生的事情是从箭头函数中得到一个布尔值 valuereturn 并存储在 allThere 中,但实际上发生的是整个 function 存储在该变量中,而不是函数的 result。我可能在这里遗漏了一些基本的东西。

(附带一个问题,我想知道有没有办法让箭头函数return直接给外部函数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 后 return:

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']]));

So what I am hoping to happen is to have a boolean value returned from the arrow function and stored in allThere

为此,您必须调用 函数。同时定义和调用一个函数称为IIFE("inline-invoked"[或"immediately-invoked"]"function expression"):

    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);

(As a side question, I am wondering if there is a way to make the arrow function return a value directly to the external function mutations(arr)).

是的,因为函数关闭它出现的上下文中的变量,所以你可以做:

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

...但同样,没有理由在那里使用函数。

你只是在给一个函数赋值,而不是执行该函数。这样看起来甚至没用。使用 every:

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