无论如何我可以使用循环来减少我的jQuery代码吗?

时间:2017-10-20 11:03:29

标签: javascript jquery loops javascript-objects

我正在研究一种路线规划器,我对我写的重复代码的数量不满意,特别是计算是真正的“冲洗和重复”事件。我想知道是否有人可以建议(举例)给我一个方法来减少这段代码?

目前,我使用$.each从输入字段中获取值,然后将其存储在object中。在此之后,我单独访问每个已定义的对象以执行计算和工作。我想我可能已经过度工作了一点!

首先让我向您展示一个简单的HTML,其中包含我从中收集数据的输入字段。

<div id="plot1" class="plotrow">
    <div class="lat">
        <input id="plot1_lat" />
    </div>
    <div class="lon">
        <input id="plot1_long" />
    </div>
</div>

<div id="plot2" class="plotrow">
    <div class="lat">
        <input id="plot2_lat" />
    </div>
    <div class="lon">
        <input id="plot2_long" />
    </div>
</div>

...

好的,在这个阶段我转移到jQuery来获取任何值(这将是纬度和经度坐标)。我将这些信息存储在一个对象中。

//Object is defined
var obj = {};

//Values are passed in
$('.plotrow').each(function () {
    obj[this.id] = {
        lat: $(this).find('.lat input').val(),
        lon: $(this).find('.lon input').val()
    };
});

在这个阶段,我需要开始为收集到的信息做工作。在这里,我将值传递给一个将它们转换为弧度的函数。

plot1LatRad = deg2rad(obj.plot1.lat);
plot1LonRad = deg2rad(obj.plot1.lon);
plot2LatRad = deg2rad(obj.plot2.lat);
plot2LonRad = deg2rad(obj.plot2.lon);
plot3LatRad = deg2rad(obj.plot3.lat);
plot3LonRad = deg2rad(obj.plot3.lon);

如您所见,我可以单独访问每个绘图值。接下来会发生什么,我计算出位置之间的差异。

//Location A
var AtoBLat = plot2LatRad - plot1LatRad;
var AtoBLon = plot2LonRad - plot1LonRad;
AtoBSum = Math.pow(Math.sin(AtoBLat / 2), 2) + Math.cos(plot1LatRad) * Math.cos(plot2LatRad) * Math.pow(Math.sin(AtoBLon / 2), 2);
AtoBSqrt = 2 * Math.atan2(Math.sqrt(AtoBSum), Math.sqrt(1 - AtoBSum));
AtoBMiles = AtoBSqrt * Rm;
AtoBRound = round(AtoBMiles);
miles1 = AtoBRound * 0.86898;

//Location B
var BtoCLat = plot3LatRad - plot2LatRad;
var BtoCLon = plot3LonRad - plot2LonRad;
BtoCSum = Math.pow(Math.sin(BtoCLat / 2), 2) + Math.cos(plot2LatRad) * Math.cos(plot3LatRad) * Math.pow(Math.sin(BtoCLon / 2), 2);
BtoCSqrt = 2 * Math.atan2(Math.sqrt(BtoCSum), Math.sqrt(1 - BtoCSum));
BtoCMiles = BtoCSqrt * Rm;
BtoCRound = round(BtoCMiles);
miles2 = BtoCRound * 0.86898;

正如你所看到的那样,它变得非常重复并且非常臃肿。我可以循环完成这项工作吗?任何人都可以建议一种有用的方法吗?为了简洁起见,我只展示了几个要点但是这个应用程序有多达10个区域你也可以绘制一条路线,所以上面的代码会变得很大。

2 个答案:

答案 0 :(得分:1)

如果您有多个图,代码可能会爆炸,这是正确的,但这就是函数和循环存在的原因。下面,我建议使用函数locationDiff的解决方案,它采用两个绘图配置并根据需要吐出它们之间的距离,稍后引入循环以循环通过配置对象并将结果存储在最终数组中

// does the distance calculation between two plot configurations
function locationDiff(plot1, plot2) {
    let AtoBLat = deg2rad(plot2.lat) - deg2rad(plot1.lat);
    let AtoBLon = deg2rad(plot2.lon) - deg2rad(plot1.lon);
    let AtoBSum = Math.pow(Math.sin(AtoBLat / 2), 2) + Math.cos(deg2rad(plot1.lat)) * Math.cos(deg2rad(plot2.lat)) * Math.pow(Math.sin(AtoBLon / 2), 2);
    return (round((2 * Math.atan2(Math.sqrt(AtoBSum), Math.sqrt(1 - AtoBSum))) * Rm) * 0.86898);
}

// stores the results of calling `locationDiff` on the plots
let diffs = [];
// captures the keys of the different plot configurations
let objKeys = Object.keys(obj);
// loops through the keys to calculate and store the distances
objKeys.forEach((key, index) => {
    // the next key in the keys array
    let nextKey = objKeys[index + 1];
    // if not at the end of the array yet, push the result in the final array
    if (nextKey) {
        diffs.push(locationDiff(obj[key], obj[nextKey]));
    }
});

希望这有帮助。

答案 1 :(得分:0)

出现错误,因为我不知道Rm是什么:

$("form").append(
  template("plot1"),
  template("plot2"),
  "<input type=\"submit\">"
).on("submit", function (ev) {
  ev.preventDefault();
  calculateMiles(
    this.elements.plot1_lat.value,
    this.elements.plot1_long.value,
    this.elements.plot2_lat.value,
    this.elements.plot2_long.value
  );
});

function template (id) {
  return ""
  + "<div id=\"" + id + "\" class=\"plotrow\">"
  +   "<div class=\"lat\">"
  +     id + " lat <input name=\"" + id + "_lat\" />"
  +   "</div>"
  +   "<div class=\"lon\">"
  +     id + " lng <input name=\"" + id + "_long\" />"
  +   "</div>"
  + "</div>";
}

function calculateMiles (plot1LatRad, plot1LonRad, plot2LatRad, plot2LonRad) {
  var AtoBLat = plot2LatRad - plot1LatRad;
  var AtoBLon = plot2LonRad - plot1LonRad;
  var AtoBSum = Math.pow(Math.sin(AtoBLat / 2), 2) + Math.cos(plot1LatRad) * Math.cos(plot2LatRad) * Math.pow(Math.sin(AtoBLon / 2), 2);
  var AtoBSqrt = 2 * Math.atan2(Math.sqrt(AtoBSum), Math.sqrt(1 - AtoBSum));
  var AtoBMiles = AtoBSqrt * Rm;
  var AtoBRound = round(AtoBMiles);
  return AtoBRound * 0.86898;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form></form>