如何在javascript

时间:2015-09-15 10:03:15

标签: javascript jquery

我有这段代码:

我想要它接受这个功能

function (x1,y1,x2, y2,x3, y3, x4, y4, xToCheck, yToCheck, Allowance);

这是var xvar y

的可能组合
var x1 = x1 - x2;
var y1 = y1 - y2;
var x2 = x2 - x3;
var y2 = y2 - y3;
var x3 = x3 - x4;
var y3 = y3 - y4;
var x4 = x2 - x4;
var y4 = y2 - y4;
var x5 = x1 - x3;
var y5 = y1 - y3;

注意:上面的函数只能接受一组var var x1var y1,我想要的是让我的函数更具动态性,以便它可以接受另一个var的集合。

5 个答案:

答案 0 :(得分:0)

你的"津贴" (公差)应该在距离点线上。了解如何计算:

https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line

答案 1 :(得分:0)

您希望函数采用未确定/动态的坐标集x1, y1 ... xn, yn吗?

然后你可以为所有坐标使用单个参数(数组或对象),如下所示:

ST.PT.isMouseOnLine = function (points, xToCheck, yToCheck, Allowance) {}

然后传递一系列点数:

ST.PT.isMouseOnLine([ {x: 10, y:10}, { x:20, y:30}, { x:30, y:10} ], 15, 15, 10 );

因此您可以迭代points数组并对每个点进行检查。

答案 2 :(得分:0)

你的意思是,参数的数量是可变的吗? 我想你只是使用数组类型参数 像这样:

function (xs,ys, xToCheck, yToCheck, Allowance){
    var newxs,newys;
    newxs[0]=xs[0]-xs[1];//compute newxs,newys from xs,ys
    ...
}

使用一些算法从xs和ys计算newxs。 像这样:

//just a example,it's not correct
for(int i=0;i<x.length;i++){
    newxs[i]=xs[i]-xs[i+1];
    newys[i]=ys[i]-ys[i+1];
    ...
}

答案 3 :(得分:0)

如果你想要发送变量的可选默认值 - 正如你在评论中提到的那样 - 那么使用这个结构:

我们希望xToCheck, yToCheck, Allowance是可选的:

ST.PT.isMouseOnLine = function (x1, y1, x2, y2, _xToCheck, _yToCheck, _Allowance)   {

    //Get the variables:
    xToCheck = _xToCheck || 5; //replace value with default value or variable.
    yToCheck = _yToCheck || 5; //same
    Allowance = _Allowance || 0; //same

    //Calculate:
    var x = x1 - x2;
    var y = y1 - y2;
    var m = y / x;

    /* rest of your code */
}

请注意,作业variable = var1 || var2表示如果var1未定义,则将等号设置为var2

答案 4 :(得分:0)

您可以使用arguments对象迭代传递给函数的所有参数。这样,您可以简单地删除最后3个参数(xToCheck,yToCheck和Allowance)并迭代结果值以填充动态X和Y数组,如下所示:

function arbitraryArguments() {
    // first, convert function arguments into an array
    var args = Array.prototype.slice.call(arguments);

    // then get the last 3 arguments, which are always present
    var
        Allowance = args.pop(),
        yToCheck  = args.pop(),
        xToCheck  = args.pop(),
        x         = [],
        y         = [];

    // ... and fill-in the X and Y arrays from what's left
    for (var i in args) {
        if (i % 2) {
            y.push(args[i]);
        } else {
            x.push(args[i]);
        }
    }

    // ... do whatever you need with all the X and Y values
    //     in these x and y arrays

    for (var a in x) {
        console.log('x' + a + ' = ' + x[a]);
        console.log('y' + a + ' = ' + y[a]);
    }

    console.log('Allowance = ' + Allowance);
    console.log('yToCheck = ' + yToCheck);
    console.log('xToCheck = ' + xToCheck);
}

arbitraryArguments(1, 2, 3, 4, 5, 6, 7, 8, 111, 222, 1010);

JSFiddle:https://jsfiddle.net/tz1t6cmn/