根据提示存储坐标并计算距离

Store coordinates from prompt and calculate the distance

本文关键字:计算 距离 坐标 存储 提示      更新时间:2023-09-26

我研究坐标之间的距离计算,我建立了一些工作良好的东西。

var pointsCoordinates = [[5,7],[5,8],[2,8],[2,10]];
function lineDistance(points) {
  var globalDistance = 0;
  for(var i=0; i<points.length-1; i++) {
    globalDistance += Math.sqrt(Math.pow( points[i+1][0]-points[i][0] , 2 ) + Math.pow( points[i+1][1]-points[i][1] , 2 ));
  }
  return globalDistance;
}
console.log(lineDistance(pointsCoordinates));

我想稍微改进一下,发送一个提示来存储用户发送的坐标。

的例子:

alert(prompt("send me random coordinates in this format [,] and I will calculate the distance))

我想存储这些坐标,用我的函数计算距离。

我知道我必须使用push,但它不起作用,有人可以帮我写吗?我知道这很简单,但是……我做不到。

非常感谢

工作和测试的代码。从提示符中获取坐标,传递给lineDistance函数,并将传递的字符串转换为数组

function lineDistance(points) {
  var globalDistance = 0;
  var points = JSON.parse(points); // convert entered string to array
  for(var i=0; i<points.length-1; i++) {
    globalDistance += Math.sqrt(Math.pow( points[i+1][0]-points[i][0] , 2 ) + Math.pow( points[i+1][1]-points[i][1] , 2 ));
  }
  return globalDistance;
}
var pointsCoordinates = prompt("send me random coordinates in this format [,] and I will calculate the distance");
if (coordinates != null)
    console.log(lineDistance(coordinates)); //[[5,7],[5,8],[2,8],[2,10]]
else
    alert("Entered value is null");

var userPrompt = prompt("send me random coordinates");// e.g [100,2] [3,45] [51,6]
var pointsCoordinates = parseCoordinates(userPrompt);
function parseCoordinates(unparsedCoord) {
    var arr = unparsedCoord.split(" ");
    var pair;
    for (var i = 0; i < arr.length; i++) {
        pair = arr[i];
        arr[i] = pair.substr(1, pair.length - 2).split(",")
    }
    return arr;
}
function lineDistance(points) {
    var globalDistance = 0;
    for(var i = 0; i < points.length - 1; i++) {
        globalDistance += Math.sqrt(Math.pow(points[i + 1][0] - points[i][0], 2) + Math.pow(points[i+1][1]-points[i][1], 2));
    }
    return globalDistance;
}
console.log(pointsCoordinates);
console.log(lineDistance(pointsCoordinates));

如果你使用prompt,你不需要用alert包裹它。

此外,prompt将返回字符串值,因此您需要解析您返回的数据(除非您对字符串很好)

在本例中,由于希望返回一个数组的点,因此解析可能比转换值更复杂。我的建议是使用JSON.parse()来解析输入数组

在您的情况下,您可以使用以下代码

var coordString = prompt("send me random coordinates in this format [,] and I will calculate the distance");
try {
    var coordinates = JSON.parse(coordString);
    // now check that coordinates are an array
    if ( coordinates.constructor === Array ) {
        // this might still fail if the input array isn't made of numbers
        // in case of error it will still be caught by catch
        console.log(lineDistance(coordinates));
    }    
} catch(error) {
    // if something goes wrong you get here
    alert('An error occurred: ' + error);
}

我建议阅读MDN文档中的prompt(),如果你想知道你还可以用它们做什么。此外,如果您想从文本字符串中解析值,JSON.parse()的文档也很有用。