javascript函数两点之间的距离

javascript函数两点之间的距离,javascript,function,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 fou

我已经学习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));

你把暗示用错地方了。
distanceTo
函数应该包含四个参数。
根据提示,我不想麻烦使用
构造函数(尽管我通常喜欢这种想法,但它似乎不是这个问题想要的。只需使用
距离to(x,y,x1,y1)
,我想你不会有任何问题。

Point
构造函数应该只有两个参数
x
y
。而
distance to
应该使用
x
y
点和另一个点(作为参数传递的点)

功能点(x,y){//仅x和y
这个.x=x;
这个。y=y;
this.distanceTo=函数(点)
{
var dx=this.x-point.x;//增量x
var dy=this.y-point.y;//增量y
var dist=Math.sqrt(dx*dx+dy*dy);//距离
返回距离;
};
}
var newPoint=新点(10100);
var nextPoint=新点(25,5);

console.log(newPoint.distanceTo(nextPoint));
根据您的代码,有几种不同的方法可以实现这一点,但由于您的函数需要4个输入,所以我选择了这一种

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

var points = new Point (10,100,25,5);
console.log(points.distanceTo()
))

您也不需要设置变量然后返回它,您只需返回公式即可。

尝试以下操作:
功能点(x,y){
这个.x=x;
这个。y=y;
this.distanceTo=函数(点)
{
var distance=Math.sqrt((Math.pow(point.x-this.x,2))+(Math.pow(point.y-this.y,2)))
返回距离;
};
}
var newPoint=新点(10100);
var nextPoint=新点(20,25);

console.log(newPoint.distanceTo(nextPoint))
您的函数
函数点(x,y,x1,y1)
获取四个参数,但您仅使用其中两个参数声明它。 在
distance to
函数中,您应该与调用函数的参数
点相关

应该是这样的,<代码>点.x
为您提供传递对象的“x”值

@编辑:我对这个“问题”的解决方案是


您将“点”作为参数传递,但您没有在函数中使用它……根据您的说明,看起来他们只是希望您创建一个单独的函数,该函数接受4个参数并返回结果。您的
对象超出了该要求,只需要2个参数。您也有4个函数参数,但在执行
var newPoint=newPoint(10100)时只传递了2个
您似乎希望使用一个名为
距离
的函数,而不是
,将坐标对传递给它,然后执行该计算并返回
距离
值。非常感谢,但是我不太明白我的4个参数在整个函数中是如何工作的。@GerardoLeon请看我添加的注释。代码没有错,如果参数小于或大于函数期望值,javascript中的函数不会抛出错误。函数使用未提供的参数时出错。Parameter中的过量将永远不会抛出错误。
var Point = function (x,y) {
  this.x = x;
  this.y = y;

  this.distanceTo = function (point) {
    let calculations = Math.sqrt((Math.pow(point.x-this.x,2))+(Math.pow(point.y-this.y,2)));

    return calculations;
  }
}

var firstPoint = new Point(0,0);
var secPoint = new Point(2,2);

console.log(firstPoint.distanceTo(secPoint));