繁体   English   中英

没有从 Javascript 函数返回

[英]no return from Javascript function

我根据我在 Stack 上阅读的信息编写了这个脚本。 它从 API 调用数据,并应该将方向度数转换为基数。 当我运行它时,我没有输出。 检查页面时没有错误。 当我通过 Fiddle 运行它时,我没有发现语法错误。

我想我可以简单地用一个数字(我试过 45)代替 num 并使脚本运行无济于事,所以我可以使用专家的眼光。 谢谢你。

var settings = {
  "url": "https://api.stormglass.io/v1/weather/point?lat=40.370181&lng=-73.934193&key=...",
  "method": "GET",
  "timeout": 0,
};

$.ajax(settings)
.fail(function(a,b,c) { console.log(a.responseJSON) })
.done(function(response) {
  console.log(response);

  variconwndr24 = function degToCompass(num) {
    var num = response.hours[17].windDirection[1].value;;
    while (num < 0) num += 360;
    while (num >= 360) num -= 360;
    val = Math.round((num - 11.25) / 22.5);
    arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE",
      "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"
    ];
    return arr[Math.abs(val)];
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

首先,尝试这样的事情:

var settings = {
  "url": "https://api.stormglass.io/v1/weather/point?lat=40.370181&lng=-73.934193&key=xdvfd",
  "method": "GET",
  "timeout": 0,
};

$.ajax(settings).done(function(response) {
  console.log(response);
  var degrees = response.hours[17].windDirection[1].value;
  variconwndr24 = degToCompass(degrees);
  console.log(variconwndr24);
  return variconwndr24;
});

function degToCompass(num) {
    while (num < 0) num += 360;
    while (num >= 360) num -= 360;
    val = Math.round((num - 11.25) / 22.5);
    arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE",
      "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"
    ];
    console.log(arr[Math.abs(val)]);
    return arr[Math.abs(val)];
  }

按照您的方式,degToCompass 从未真正被调用,并且num参数变得多余,因为您立即重新定义了它。

主要问题在于 done 的回调函数。 您正在定义一个函数degToCompass ,但从未调用过该函数。 此外,您正在为传递的函数重新定义参数。 如果您只是覆盖它,则将 num 作为参数传递是没有意义的。 相反,只需将响应的所需值作为参数传递。 另外,为了可读性和维护起见,请尝试将其分解如下:

 const arr = [ "N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW" ]; var settings = { "url": "https://api.stormglass.io/v1/weather/point?lat=40.370181&lng=-73.934193&key=...", "method": "GET", "timeout": 0, }; function degToCompass(num) { while (num < 0) { num += 360; } while (num >= 360) { num -= 360; } val = Math.round((num - 11.25) / 22.5); return arr[Math.abs(val)]; } function faiureCallback(a, b, c) { console.log(a.responseJSON); } function doneCallback(response) { // Do some stuff var num = response.hours[17].windDirection[1].value;; return degToCompass(num) } $.ajax(settings) .fail(faiureCallback) .done(doneCallback);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM