gpt4 book ai didi

javascript - 未定义值、变量范围问题

转载 作者:行者123 更新时间:2023-12-03 03:17:39 26 4
gpt4 key购买 nike

我不确定为什么我的控制台中出现未定义。我阅读了有关作用域变量的内容,并了解到在作用域之外定义变量应该使该变量可以在特定函数作用域之外访问。不确定我在这里做错了什么:

const history = createHistory();
const location = history.location;
let loc;
const listen = history.listen((location) => {
loc = `${location.search}${location.hash}`;
return loc;
})
console.log(loc);

我的控制台正在记录未定义

最佳答案

这是因为您在分配值之前就记录了 loc。它只是被初始化,因此它的值为未定义。当调用传递给listen的回调时,它将被赋值。要记录正确的值,您需要将代码更改为:

const history = createHistory();
const location = history.location;
let loc;
const listen = history.listen((location) => {
loc = `${location.search}${location.hash}`;
console.log(loc);
})
<小时/>

我认为 listen 是异步的,因此在这种情况下,您无法真正返回它或使用您在问题中描述的方式。但是,一旦进入 listen 回调,您就可以将该值传递给其他回调。请参阅How do I return the response from an asynchronous call?了解更多解释和示例。

关于javascript - 未定义值、变量范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46697385/

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