gpt4 book ai didi

javascript - 如何让我通过 forEach 传递的函数引用其他范围内的变量?

转载 作者:行者123 更新时间:2023-12-01 16:09:47 25 4
gpt4 key购买 nike

我不知道为什么我的 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 中,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."

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

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

关于javascript - 如何让我通过 forEach 传递的函数引用其他范围内的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63321825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com