比较javascript数组中的值,并确保每个值至少相隔10

时间:2013-08-13 18:38:52

标签: javascript

有以下数组包含子数组(每个子数组是HTML5画布上的一对坐标):

var myArray = [[364, 124], 
               [192, 272], 
               [209, 217], 
               [332, 227], 
               [241, 273], 
               [356, 387], 
               [104, 185], 
               [361, 380], 
               [297, 390], 
               [371, 311], 
               [191, 293]];

如何比较每对坐标并确保每个值至少相差10个。

例如: 将数字272(从索引为1的数组)与数字273(从索引为4的数组)进行比较 - 因为只有1个,所以将10加到一个值。

以下是我的尝试:

这里我随机生成数字,但我可以只关注最后生成的数字。

function crosses(){
    var crossx, crossy, oldCrossx, oldCrossy, col;
    for(var i=0; i<=10; i++){

    crossx = randomFromInterval(100, xw-100);
    crossy = randomFromInterval(100, xh-100);


    if(crossesPos.length > 0){
        oldCrossx = crossesPos[i-1][0];
        oldCrossy = crossesPos[i-1][1];
        if(crossx - oldCrossx < 20){
            crossx += 10;
        }
        if(crossx - oldCrossx < -20 ){
            crossx -= 10;
        }
        if(crossy - oldCrossy < 20){
            crossy += 10;
        }
        if(crossy - oldCrossy < -20 ){
            crossy -= 10;
        }
    }
}

所以我想到了一种新方法,并在所有数字生成并且已经存在于数组中之后更改数据。

我在想我采取了错误的做法:

也许我需要一种更好的方法来生成数字 - 现在我正在使用此函数在特定间隔之间生成数字。

function randomFromInterval(from,to){
        return Math.floor(Math.random()*(to-from+1)+from);
    }

1 个答案:

答案 0 :(得分:1)

jsFiddle Demo

var myArray = [
    [364, 124],
    [192, 272],
    [209, 217],
    [332, 227],
    [241, 273],
    [356, 387],
    [104, 185],
    [361, 380],
    [297, 390],
    [371, 311],
    [191, 293]
];

function distTen(element, index, array) {
    for (x = 0; x < 10; x++) {
        if (Math.abs(element[0] - array[x][0]) < 10) array[x][0] += 10;
        if (Math.abs(element[1] - array[x][1]) < 10) array[x][1] += 10;
    }
}

function logIt(element, index, array) {
    console.log("a[" + index + "] = " + element);
}
myArray.forEach(distTen);
myArray.forEach(logIt);

<强>结果

a[0] = 394,134
a[1] = 202,302
a[2] = 229,227
a[3] = 342,247
a[4] = 251,303
a[5] = 376,407
a[6] = 114,195
a[7] = 381,390
a[8] = 307,410
a[9] = 401,321
a[10] = 191,293