【问题标题】:Is there anyway I can reduce my jQuery code by using a loop?无论如何我可以通过使用循环来减少我的 jQuery 代码吗?
【发布时间】:2017-10-20 11:03:28
【问题描述】:

我正在开发一种路线规划器,我对自己编写的大量重复代码不满意,尤其是对于真正的“冲洗和重复”事件的计算。我想知道是否有人可以建议(举个例子)让我减少这段代码的方法?

目前我使用$.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 个区域,您也可以绘制路线,因此上面的代码会变得非常大。

【问题讨论】:

  • 如果你的代码是完整的、有效的,只是需要改进,那么它应该在 Code Review 上。该站点主要用于修复损坏的代码。
  • 您是否尝试过创建class Location
  • 你为你的最后一个位置做了什么?你做 CtoARound 吗?还有,一旦你计算了这些值,你会如何处理它们

标签: javascript jquery loops javascript-objects


【解决方案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]));
    }
});

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    有一个错误,因为我不知道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>

    【讨论】:

      猜你喜欢
      • 2015-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      • 2014-01-13
      • 2019-03-01
      • 2019-04-20
      • 1970-01-01
      相关资源
      最近更新 更多