压缩if语句以查找值适合的范围

时间:2018-06-28 06:19:52

标签: javascript if-statement fitbit

所以我试图为Fitbit Ionic制作一个指南针应用程序,它可以工作,但是这段代码让我很生气。我知道有一种方法可以压缩它,但我不知道如何。它应该取一个整数,然后告诉我相应的基本方向是什么。

如果语句可以压缩的话,看起来会好得多。任何建议或解决方案都将不胜感激。

geolocation.watchPosition(function(position) {
var headingDir;
var headingDeg;
headingDeg = position.coords.heading ? position.coords.heading.toFixed(2) : 0

//This long boi
 if (headingDeg >= 22.5 & headingDeg < 67.5) {
  headingDir = "NE";
 } else if (headingDeg >= 67.5 & headingDeg < 112.5) {
  headingDir = "E"
 } else if (headingDeg >= 112.5 & headingDeg < 157.5) {
  headingDir = "SE"
 } else if (headingDeg >= 157.5 & headingDeg < 202.5) {
  headingDir = "S"
 } else if (headingDeg >= 202.5 & headingDeg < 247.5) {
  headingDir = "SW"
 } else if (headingDeg >= 247.5 & headingDeg < 292.5) {
  headingDir = "W"
 } else if (headingDeg >= 292.5 & headingDeg < 337.5) {
  headingDir = "NW"
 } else {
  headingDir = "N"
 };

})

2 个答案:

答案 0 :(得分:2)

由于每个范围相差相同的量(45),因此可以为方向字符串创建一个数组,然后立即计算所需的方向字符串的索引:

const headingStrs = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N'];
const getHeading = (deg) => headingStrs[Math.floor((deg + 22.5) / 45)];

console.log(getHeading(30)); // NE
console.log(getHeading(300)); // NW
console.log(getHeading(170)); // S
console.log(getHeading(22.5)); // NE
console.log(getHeading(15)); // N

答案 1 :(得分:0)

class DeploymentOnUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = DeploymentOnUserModel
        fields = '__all__'

您可以将条件和结果作为对象存储到数组中,并使用let headingDeg = 23; let headingDir = ''; let headingObjArr = [ {minDeg: 22.5, maxDeg: 67.5, value: 'NE'}, {minDeg: 67.5, maxDeg: 112.5, value: 'E'}, {minDeg: 112.5, maxDeg: 157.5, value: 'SE'} ] headingDir = headingObjArr.find(function(element) { return headingDeg >= element.minDeg && headingDeg < element.maxDeg }); console.log(headingDir.value)来获取值