javascript函数两点之间的距离

Ger*_*eon 3 javascript function

我已经学习 JavaScript 几天了。我的程序的语法和语义有问题,我可以运行这个简单的问题。我不知道出了什么问题

//2. **Distance between two points**. Create a 
//function that calculate the distance between two points 
//(every point have two coordinates: x, y). _HINT: Your function 
//Should receive four parameters_.


    function Point(x,y,x1,y1){
    this.x = x;
    this.y = y;
    this.x1 = x1;
    this.y1 = y1;

    this.distanceTo = function (point)
    {
        var distance = Math.sqrt((Math.pow(this.x1-this.x,2))+(Math.pow(this.y1-this.y,2)))
        return distance;
    };
}

var newPoint = new Point (10,100);
var nextPoint = new Point (25,5);


console.log(newPoint.distanceTo(nextPoint));
Run Code Online (Sandbox Code Playgroud)

小智 12

试试这个:

    function Point(x,y){
    this.x = x;
    this.y = y;
    

    this.distanceTo = function (point)
    {
        var distance = Math.sqrt((Math.pow(point.x-this.x,2))+(Math.pow(point.y-this.y,2)))
        return distance;
    };
}

var newPoint = new Point (10,100);
var nextPoint = new Point (20,25);

console.log(newPoint.distanceTo(nextPoint))
Run Code Online (Sandbox Code Playgroud)

在 distanceTo 函数中,您需要引用 point.x 和 point.y,因为它们是 nextPoint 的点。

希望这有帮助:3