You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS全局变量不生效 函数外无法获取内部风速等变量值

问题核心原因

你遇到的undefined问题和全局挂载方案无关,是两个基础JS机制导致的:

  • fetch是异步网络请求,JS引擎发起请求后不会等待接口返回,会直接执行后续代码。你写在x()调用外层的console.log(windspeed)运行时,接口还没返回结果,处理数据的openweather函数根本没执行,变量自然没有被赋值。你在函数内能正常打印、能给页面元素赋值,是因为这部分逻辑写在.then回调里,会等接口请求成功后才触发,执行时机比外层的console.log晚。
  • 你在openweather函数内直接给windspeed、winddegree等变量赋值时没有加let/const/var声明,非严格模式下虽然会默认成为全局变量,但因为前面说的时序问题,你访问的时候变量还没被赋值,就算手动用globalThis挂载也不会生效。
  • 额外语法问题:你原有代码里fetch的请求URL被拆成了两行,实际运行会触发语法错误,需要拼接成完整单行。
修复代码

不要试图在异步请求外层直接读取变量,正确的写法是先声明全局存储对象,等接口返回更新数据后,再执行依赖这些数据的逻辑:

// 全局声明存储气象数据的对象
const weatherInfo = {
  windspeed: null,
  winddegree: null,
  airtemp: null,
  airpressure: null,
  knots: null
}

function fetchAndUpdateWeather() {
  // 注意URL不要换行
  fetch('http://api.openweathermap.org/data/2.5/weather?lat=33.778726&lon=-118.377751&appid=c8ba55aeb3b4aeb0add9badde352f0df&units=imperial')
    .then(res => res.json())
    .then(data => {
      // 接口返回后更新全局变量
      weatherInfo.windspeed = parseInt(data.wind.speed)
      weatherInfo.winddegree = parseInt(data.wind.deg)
      weatherInfo.airtemp = parseInt(data.main.temp)
      weatherInfo.airpressure = parseInt(data.main.pressure)
      weatherInfo.knots = parseInt(data.wind.speed * 0.868976)

      // 原有页面赋值逻辑
      document.getElementById("windspeedx").textContent = weatherInfo.windspeed
      document.getElementById("winddirectionx").textContent = weatherInfo.winddegree
      document.getElementById("airtemperaturex").textContent = weatherInfo.airtemp
      document.getElementById("airpressurex").textContent = weatherInfo.airpressure
      document.getElementById("knotsx").textContent = weatherInfo.knots

      // 所有需要用到风速、风向等数据的逻辑,都在这里调用
      runLogicWithWeatherData()
    })
    .catch(err => console.error('请求天气数据失败:', err))
}

function runLogicWithWeatherData() {
  // 在这里写你需要用到气象数据的业务逻辑,此时全局变量已经更新完成
  console.log('当前风速:', weatherInfo.windspeed)
  console.log('当前风向:', weatherInfo.winddegree)
}

// 首次加载拉取数据
fetchAndUpdateWeather()
// 每15秒自动刷新数据
setInterval(fetchAndUpdateWeather, 15000)
关键注意点

所有依赖天气数据的逻辑,绝对不能写在fetchAndUpdateWeather()调用的同级位置,也不能写在fetch调用的后面没有被.then包裹的位置——这些位置的代码执行时机永远早于接口返回,一定会拿到null或者undefined。必须等接口返回、全局变量更新完成后,再执行相关逻辑。

内容的提问来源于stack exchange,提问作者Matthew Brach

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 16:54:36