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

如何修改JS箭头函数实现found变量全局可用 箭头函数作用域问题

问题原因

你的found变量是在finder箭头函数内部用var声明的,属于函数级局部变量,作用域仅限制在函数体内,外部自然无法访问。你之前提前在外部声明失败,大概率是在函数内部又重复加了var关键字声明found,相当于创建了同名局部变量覆盖了全局变量。

可用解决方案

方案1:全局提前声明,函数内直接赋值

不要在函数内部重复用var/let/const声明found,直接对全局声明的变量赋值即可:

var mK = [
    { latitude: -34.906874, longitude: -56.206150 },
    { latitude: -34.888571, longitude: -56.191530 },
    { latitude: -34.880967, longitude: -56.163187 },
    { latitude: -34.895048, longitude: -56.155973 },
    { latitude: -34.911097, longitude: -56.133299 },
    { latitude: -34.920388, longitude: -56.146530 },
];
// 提前在全局声明found
var found = null;

const finder = () => {
  var firstfind = findNearest({ latitude: coords.latitude, longitude: coords.longitude }, mK);
  // 这里不要加var,直接给全局found赋值
  found = getPreciseDistance(
    { latitude: coords.latitude, longitude: coords.longitude },
    { latitude: firstfind.latitude, longitude: firstfind.longitude }
  );
  console.log(found)
  alert( JSON.stringify(found));
}

// 调用finder之后就可以在全局使用found了
finder();
console.log('全局拿到的found值:', found);

方案2:挂载到全局window对象(浏览器环境适用)

直接在函数内把值挂到window上,无需提前声明:

const finder = () => {
  var firstfind = findNearest({ latitude: coords.latitude, longitude: coords.longitude }, mK);
  // 直接挂载到window,全局可通过window.found访问
  window.found = getPreciseDistance(
    { latitude: coords.latitude, longitude: coords.longitude },
    { latitude: firstfind.latitude, longitude: firstfind.longitude }
  );
  console.log(found)
  alert( JSON.stringify(found));
}

方案3:函数返回值接收

如果不想污染全局作用域,可以让finder返回计算结果,调用时用变量接收:

const finder = () => {
  var firstfind = findNearest({ latitude: coords.latitude, longitude: coords.longitude }, mK);
  var found = getPreciseDistance(
    { latitude: coords.latitude, longitude: coords.longitude },
    { latitude: firstfind.latitude, longitude: firstfind.longitude }
  );
  console.log(found)
  alert( JSON.stringify(found));
  // 新增return语句返回结果
  return found;
}

// 调用时接收返回值即可
const globalFound = finder();
console.log('拿到的结果:', globalFound);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:06:04