2017-10-11 28 views
0

我不知道为什么我在控制台中获得undefined。我阅读了关于范围变量的知识,并且知道在范围外定义一个变量应该使该变量可以在特定函数范围之外访问。 不知道我在做什么错在这里:未定义的值,变量范围问题

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

我的控制台登录undefined

+1

请注意,'location'是'window'上的一个全局变量,您可以通过'window.location'或甚至'location'访问它。 – JohnnyCoder

回答

1

也就是说怎么一回事,因为你正在登录loc已分配一个值之前。它仅被初始化,因此其值为undefined。当回调传递给listen时,它将被赋值。要登录,你需要你的代码更改为正确的值:

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

我认为listen是asynchronus,所以在这种情况下,你真的不能返回,或使用你在你的问题中所述的方式。但是,一旦您处于listen回调中,您可以将该值传递给其他回调。有关更多解释和示例,请参阅How do I return the response from an asynchronous call?

+0

感谢您的回复!这里的问题是我想在'listen'函数之外使用'loc'。截至目前,我只有一个console.log用于简化。但是我想要做的就是一旦我给'listen'里面的'log'赋值,我想在该列表的外部使用'loc'。那可能吗? – vanegeek

0

console.log(loc);该变量未定义的时刻。

由于此功能

(location) => { loc = `${location.search}${location.hash}`; } 

后,它将运行。

0

问题是,history.listen方法仅在位置更改时调用。 history.listen(...)调用声明了当历史记录发生变化时应该调用的代码,但该代码在那时尚未运行。

伪代码,这里是你已指示什么:

  • 声明一些常量和变量
  • 注册一些代码运行时的历史变迁
  • 打印出来的值(仍

    :未初始化)变量控制台

你的意思,这可能是更接近于0

const history = createHistory(); 
const location = history.location; 
let loc; 

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

您可以,但如其余的说,loc变量将不会被分配一个值,直到您更改位置,因此执行监听方法。在此之前,其值将为undefined。另外,为什么你想要有listen变量,当你已经在你的代码之上声明时返回值为loc