从文学课程中以文本方式解析课程?

时间:2018-02-25 06:27:07

标签: javascript node-red compass

所以我在节点红色中制作一个指南针,它应该以度(int)作为输入和字符串(course)作为输出:enter image description here

所以我需要带整数的函数,并给我标题字符串。怎么做简单可靠?

我必须将字符串转换为0-360度,例如:NORTH,NORTH-EAST,EAST ......

我尝试了以下内容:

var course = parseInt(courseFloatDegrees);
var courseTxt = "";
if (course >= 349 && course <= 11 || course <= 359 && course >= 349 || course === 0) courseTxt = "N";
else if (course >= 11 && course <= 33) courseTxt = "NNE";
else if (course >= 33 && course <= 56) courseTxt = "NE";
else if (course >= 56 && course <= 78) courseTxt = "ENE";
else if (course >= 78 && course <= 101 || course == 90) courseTxt = "E";
else if (course >= 101 && course <= 124) courseTxt = "ESE";
else if (course >= 124 && course <= 146) courseTxt = "SE";
else if (course >= 146 && course <= 168) courseTxt = "SSE";
else if (course >= 168 && course <= 191 || course == 180) courseTxt = "S";
else if (course >= 191 && course <= 214) courseTxt = "SSW";
else if (course >= 214 && course <= 236) courseTxt = "SW";
else if (course >= 236 && course <= 258) courseTxt = "WSW";
else if (course >= 258 && course <= 281 || course == 270) courseTxt = "W";
else if (course >= 281 && course <= 303) courseTxt = "WNW";
else if (course >= 303 && course <= 326) courseTxt = "NW";
else if (course >= 326 && course <= 349) courseTxt = "NNW";
else courseTxt = "INVALID"

但有时我什么也得不到(空 - 空字符串)或“无效”。如果没有那么多if语句,有没有人知道快速简单的方法呢?

2 个答案:

答案 0 :(得分:1)

可能有更多方法可以做到这一点,简单地说&#39;在代码中,但你的方法应该工作。它之所以没有,是因为你的if语句在N&#39; N&#39;区域。

if ((course >= 349 && course <= 11) || (course <= 359 && course >= 349) || (course === 0)) courseTxt = "N";

如果你看前两个条件,它们是不合逻辑的。超过349但不到11?这永远不会发生。如果您有7度的课程,那么目前不符合任何指定的标准。

所以要做的第一件事就是解决这个问题。您需要调整行以使用OR而不是AND

if(course < 11 || course > 349) courseTxt = "N";

现在您的代码将能够处理360/0度的任意一侧的设置。

这应该足以让你当前的代码工作,假设课程总是小于或等于360.

您询问是否有办法避免所有if语句。可能有数百种方法可以做到这一点,但除了if或case语句之外最简单的方法可能是使用数组来查找标题。这是一个如何完成它的例子。显然你可以对步长值进行硬编码,但这样你可以用任意数量的更精细的标题更新你的数组,它仍然可以工作。

function getCourse(course)
{
// define our values
var degs = 360;
var strs =
 ["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];

// make sure course is always within the expected range in case it is incremented past 360
course = course % degs;
// get the step amount based on the number of compass headings we have
var step = degs/strs.length;
// adjust for the last few degrees on the scale which will be north
if(course > degs - (step/2)) course += step/2;
// now just divide the course by the step and read off the relevant heading
var index = Math.floor(course / step);
return strs[index];
}

答案 1 :(得分:0)

尼基,

我使用类似于Toby的方法 - 计算课程字符串数组的索引:

var deg = course % 360;
var dirs = ["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW","N"];
var idx = Math.round(deg * (dirs.length-1)/360);
var dir = dirs[idx];

诀窍是重复&#34; N&#34;数组开头和结尾的元素,并使用Math.round(...)跳转到最接近的整数索引号。