gpt4 book ai didi

javascript - 在另一个函数中使用函数中的变量

转载 作者:行者123 更新时间:2023-11-28 17:35:50 28 4
gpt4 key购买 nike

我正在使用表单的 selectedIndex 为变量赋值

function getIndex() {
var departureAirportIndex = document.getElementById("mySelect").selectedIndex;

if (departureAirportIndex == 1) {
var lat2 = 13.7563309;
var lon2 = 100.5017651;
}
if (departureAirportIndex == 2){
var lat2 = 41.977226;
var lon2 = -87.836723;
}
if (departureAirportIndex == 3){
var lat2 = -37.663712;
var lon2 = 144.844788;
}

分配值后,我想在计算距离的函数中使用这些值。

function getDistance(lat1, lon1, lat2, lon2, unit) {
var lat1 = 40.730610;
var lon1 = -73.935242;
var unit = "K";
var radlat1 = Math.PI * lat1/180
var radlat2 = Math.PI * lat2/180
var theta = lon1-lon2
var radtheta = Math.PI * theta/180
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist)
dist = dist * 180/Math.PI
dist = dist * 60 * 1.1515
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist.toFixed(2)

}

如何在第二个函数中使用 lat2 和 lon2 变量?在尝试了几种选项并阅读了有关范围界定的内容后,我无法让它发挥作用。

最佳答案

您可以返回一个带有坐标的对象:

function getIndex() {
var coordinates = {}
var departureAirportIndex = document.getElementById("mySelect").selectedIndex;

if (departureAirportIndex == 1) {
coordinates.lat = 13.7563309;
coordinates.lon = 100.5017651;
}
if (departureAirportIndex == 2){
coordinates.lat = 41.977226;
coordinates.lon = -87.836723;
}
if (departureAirportIndex == 3){
coordinates.lat = -37.663712;
coordinates.lon = 144.844788;
}

return coordinates;
}

function getDistance(lat1, lon1, lat2, lon2, unit) {...}

var coordinates = getIndex();
getDistance(lat1, lon1, coordinates.lat, coordinates.lon, unit);

关于javascript - 在另一个函数中使用函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49139130/

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