回调中未定义函数参数

发布于 2025-01-10 04:50:13 字数 2372 浏览 0 评论 0原文

我正在尝试获取用户的位置,并使用它来获取城市。 我不知道为什么,但是当我调用 query 函数时,城市参数有一些值,但它没有反映在回调函数的 if 条件中。 但是,如果我用常见的字符串回调函数替换 If 条件中的城市变量,则效果很好。 数据变量是对象数组

var data = [{ District: "surat", Specialties: "eye" }, ...., {}];
getLocation();
function getLocation() {
  var lat = "";
  var lon = "";
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, showError);
  } else {
    console.log("denied");
  }
}

function showPosition(position) {
  console.log("2");
  lat = position.coords.latitude;
  lon = position.coords.longitude;
  console.log(lat);
  console.log(lon);
  displayLocation(lat, lon);
}

function showError(error) {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      console.log("User denied the request for Geolocation.");
      break;
    case error.POSITION_UNAVAILABLE:
      console.log("Location information is unavailable.");
      break;
    case error.TIMEOUT:
      console.log("The request to get user location timed out.");
      break;
    case error.UNKNOWN_ERROR:
      console.log("An unknown error occurred.");
      break;
  }
}

async function displayLocation(latitude, longitude) {
  let city = "";
  var geocoder;
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(latitude, longitude);

  await geocoder.geocode(
    {
      latLng: latlng,
    },
    function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        console.log(results);
        if (results[0]) {
          var add = results[0].formatted_address;
          var value = add.split(",");

          count = value.length;
          country = value[count - 1];
          state = value[count - 2];
          city = value[count - 3];

          console.log(city);
        } else {
          console.log("not found");
        }
      } else {
        console.log(status);
      }
    }
  );
  await query(city);
}

function query(city) {
  console.log(city); // it is printing Correctly

  var hospitals = data.filter((val) => {
    if (
      val["District"] === city &&
      val["Specialties"].toLowerCase().indexOf("eye") != -1
    ) {
      return true; //instead of city(parameter) if I put a String(For Example"Boston") it works completely fine.
    }
  });
  console.log(hospitals); //hospital array is empty instead of having some value
}

I am trying to get the location of the user and using that I am trying to get the city.
I don't why but when I call the query function, the city parameter is having some value but it is not reflected in the callback function's if condition.
However, if I replace the city variable in the If condition with the common String callback function works fine.
the data variable is the array of objects

var data = [{ District: "surat", Specialties: "eye" }, ...., {}];
getLocation();
function getLocation() {
  var lat = "";
  var lon = "";
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, showError);
  } else {
    console.log("denied");
  }
}

function showPosition(position) {
  console.log("2");
  lat = position.coords.latitude;
  lon = position.coords.longitude;
  console.log(lat);
  console.log(lon);
  displayLocation(lat, lon);
}

function showError(error) {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      console.log("User denied the request for Geolocation.");
      break;
    case error.POSITION_UNAVAILABLE:
      console.log("Location information is unavailable.");
      break;
    case error.TIMEOUT:
      console.log("The request to get user location timed out.");
      break;
    case error.UNKNOWN_ERROR:
      console.log("An unknown error occurred.");
      break;
  }
}

async function displayLocation(latitude, longitude) {
  let city = "";
  var geocoder;
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(latitude, longitude);

  await geocoder.geocode(
    {
      latLng: latlng,
    },
    function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        console.log(results);
        if (results[0]) {
          var add = results[0].formatted_address;
          var value = add.split(",");

          count = value.length;
          country = value[count - 1];
          state = value[count - 2];
          city = value[count - 3];

          console.log(city);
        } else {
          console.log("not found");
        }
      } else {
        console.log(status);
      }
    }
  );
  await query(city);
}

function query(city) {
  console.log(city); // it is printing Correctly

  var hospitals = data.filter((val) => {
    if (
      val["District"] === city &&
      val["Specialties"].toLowerCase().indexOf("eye") != -1
    ) {
      return true; //instead of city(parameter) if I put a String(For Example"Boston") it works completely fine.
    }
  });
  console.log(hospitals); //hospital array is empty instead of having some value
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

铁憨憨 2025-01-17 04:50:13

如果过滤器未通过您的条件,您必须在过滤器中返回 false - 因此,最好只写:

return val['District'] === city && val['Specialties'].toLowerCase().indexOf("eye") != -1

在这种情况下,返回值将为 Boolean > (true 如果通过,false 如果没有)。

此外,函数中未定义 data 变量。最好将其作为参数传递。

另外:data 数组中的 objects 有一个名为 Specialities 的键,但您正在过滤 Specialties

const data = [{
    District: "city1",
    Specialties: "yeseye1",
  },
  {
    District: "city1",
    Specialties: "noye1",
  },
  {
    District: "city1",
    Specialties: "yeseye2",
  },
]

console.log('====== old query ======')

function query(city) {
  console.log(city); // it is printing Correctly

  var hospitals = data.filter((val) => {
    if (val['District'] === city && val['Specialties'].toLowerCase().indexOf("eye") != -1) {
      return true; //instead of city(parameter) if I put a String(For Example"Boston") it works completely fine.
    }
  });
}

const a = query("city1")
console.log(a)

console.log('====== newQuery ======')
const newQuery = (city, data) => data.filter((val) => val['District'] === city && val['Specialties'].toLowerCase().indexOf("eye") != -1)

const b = newQuery("city1", data)
console.log(b)

编辑:避免拼写错误

有一种方法可以避免像代码中那样的拼写错误:使用 constants

const DIST = "District"
const SPEC = "Specialities"
const EYE = "eye"

const data = [{
    [DIST]: "city1",
    [SPEC]: "yeseye1",
  },
  {
    [DIST]: "city1",
    [SPEC]: "noye1",
  },
  {
    [DIST]: "city1",
    [SPEC]: "yeseye2",
  },
]

const newQuery = (city, data) => data.filter((val) => val[DIST] === city && val[SPEC].toLowerCase().indexOf(EYE) != -1)

const b = newQuery("city1", data)
console.log(b)

这样您就可以选择更简单的单词而不是复杂的字符串。

编辑2

此外,如果您设置的功能稍有不同,您可以更新此解决方案:

const DIST = "District"
const SPEC = "Specialities"
const EYE = "eye"

const data = [{
    [DIST]: "city1",
    [SPEC]: "yeseye1",
  },
  {
    [DIST]: "city1",
    [SPEC]: "noye1",
  },
  {
    [DIST]: "city1",
    [SPEC]: "yeseye2",
  },
]

const curriedQuery = (data) => (filterTerm) => (city) => data.filter((val) => val[DIST] === city && val[SPEC].toLowerCase().indexOf(filterTerm) != -1)

const queryWithCityList = curriedQuery(data) // this sets the list of cities
const queryCityListForEye = queryWithCityList(EYE) // this sets the type of hospitals

const c = queryCityListForEye("city1") // this queries the hospitals in one city -> and gives you the result
console.log(c)

如果您多次过滤特定类型医院的数据源,此解决方案似乎会更好一些。当您通过一一传递参数来创建函数时,它们会被缓存(通过 V8),因此使用它们会变得更快。 (至少理论上是这样。)

You have to return false in the filter, if it is not passing your condition - thus, it is better to just write:

return val['District'] === city && val['Specialties'].toLowerCase().indexOf("eye") != -1

In this case the return value is going to be Boolean (true if passes, false if not).

Also, the data variable is not defined in the function. It's better to pass it in as an argument.

And also: the objects in the data array have a key called Specialities, but you are filtering for Specialties

const data = [{
    District: "city1",
    Specialties: "yeseye1",
  },
  {
    District: "city1",
    Specialties: "noye1",
  },
  {
    District: "city1",
    Specialties: "yeseye2",
  },
]

console.log('====== old query ======')

function query(city) {
  console.log(city); // it is printing Correctly

  var hospitals = data.filter((val) => {
    if (val['District'] === city && val['Specialties'].toLowerCase().indexOf("eye") != -1) {
      return true; //instead of city(parameter) if I put a String(For Example"Boston") it works completely fine.
    }
  });
}

const a = query("city1")
console.log(a)

console.log('====== newQuery ======')
const newQuery = (city, data) => data.filter((val) => val['District'] === city && val['Specialties'].toLowerCase().indexOf("eye") != -1)

const b = newQuery("city1", data)
console.log(b)

EDIT: AVOIDING TYPOS

There's a way to avoid typos like the one in your code: use constants:

const DIST = "District"
const SPEC = "Specialities"
const EYE = "eye"

const data = [{
    [DIST]: "city1",
    [SPEC]: "yeseye1",
  },
  {
    [DIST]: "city1",
    [SPEC]: "noye1",
  },
  {
    [DIST]: "city1",
    [SPEC]: "yeseye2",
  },
]

const newQuery = (city, data) => data.filter((val) => val[DIST] === city && val[SPEC].toLowerCase().indexOf(EYE) != -1)

const b = newQuery("city1", data)
console.log(b)

This way you can choose easier words instead of complicated strings.

EDIT 2

Also, you could update this solution if you'd set up the function(s) a bit differently:

const DIST = "District"
const SPEC = "Specialities"
const EYE = "eye"

const data = [{
    [DIST]: "city1",
    [SPEC]: "yeseye1",
  },
  {
    [DIST]: "city1",
    [SPEC]: "noye1",
  },
  {
    [DIST]: "city1",
    [SPEC]: "yeseye2",
  },
]

const curriedQuery = (data) => (filterTerm) => (city) => data.filter((val) => val[DIST] === city && val[SPEC].toLowerCase().indexOf(filterTerm) != -1)

const queryWithCityList = curriedQuery(data) // this sets the list of cities
const queryCityListForEye = queryWithCityList(EYE) // this sets the type of hospitals

const c = queryCityListForEye("city1") // this queries the hospitals in one city -> and gives you the result
console.log(c)

This solution seems a bit better if you filter the data source for a certain type of hospital many times over. As you create functions by passing in arguments one by one they are cached (by V8), so working with them becomes faster. (At least theoretically.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文