【问题标题】:How do I get the function I pass through forEach to reference variables in other scopes?如何获取通过 forEach 传递的函数以引用其他范围内的变量?
【发布时间】:2020-08-09 02:01:40
【问题描述】:

我不知道为什么我的 findDroids 函数无法引用我的 droids 函数中的 result 变量。当我运行此代码时,我得到“未定义结果”。非常感谢任何提示/指导。我是 Javascript 新手,所以请放轻松:)

function droids(arr) {
  let result = '';
  arr.forEach(findDroids);
  return result;
}

function findDroids(value, index, arr){
  if (arr[index] == "Droids"){
    result = "Found Droids!";
  } else{
    result = "These are not the droids you're looking for."
  }
}

// Uncomment these to check your work! 
const starWars = ["Luke", "Finn", "Rey", "Kylo", "Droids"] 
const thrones = ["Jon", "Danny", "Tyrion", "The Mountain", "Cersei"] 
console.log(droids(starWars)) // should log: "Found Droids!"
console.log(droids(thrones)) //should log: "These are not the droids you're looking for."

【问题讨论】:

  • 因为 JS 具有词法作用域,并且 findDroids 没有像 let result 一样在 droids 内部声明。您的问题标题已经表明您知道它在不同的范围内 - 不,不可能创建对变量的引用或传递它们。
  • 顺便说一句,forEach 似乎在这里无论如何都是错误的工具。我认为您正在寻找 findsome

标签: javascript foreach


【解决方案1】:

因为在 JS 中 let 变量的作用域是它最近的函数。在这种情况下,result 仅在 droids 级别可用。使变量全局应该可以工作:

let result = ''; // Available everywhere

function droids(arr) {
  //let result = ''; // Available only at `droids` level
  arr.forEach(findDroids);
  return result;
}

function findDroids(value, index, arr){
  if (arr[index] == "Droids"){
    result = "Found Droids!";
  } else{
    result = "These are not the droids you're looking for."
  }
}

// Uncomment these to check your work! 
const starWars = ["Luke", "Finn", "Rey", "Kylo", "Droids"] 
const thrones = ["Jon", "Danny", "Tyrion", "The Mountain", "Cersei"] 
console.log(droids(starWars)) // should log: "Found Droids!"
console.log(droids(thrones)) //should log: "These are not the droids you're looking for."

话虽如此,使用全局变量可能不是最好的选择。您可以在 haystackhaystack.includes(needle) 中找到 needle,以便轻松检查数组是否包含您要查找的值:

const arr = ["qqq", "www", "eee"]
console.log(arr.includes("qqq") ? "Found droids" : "Not found")
console.log(arr.includes("zzz") ? "Found droids" : "Not found")

【讨论】:

  • "使变量全局化应该可以工作" - 是的,但这是一个可怕的想法。而是将findDroids 声明移到droids 函数中。
  • 我知道有多种方法可以解决这个问题。将变量移动到全局确实有效。也感谢学习一些新方法!感谢您的小费。 ??
【解决方案2】:
function droids(arr) {
  return arr.some(function(a){return a === "Droids";});
}

“一些”建议。检查“包含”的其他示例,这可能是该工作的更好工具。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 2021-11-20
    • 2011-07-11
    • 2018-12-09
    • 2014-09-17
    • 2020-10-17
    • 2019-07-30
    相关资源
    最近更新 更多