我有一个包含一些x和y位置的对象:

var positions = [
0: {x: 720, y: 389.5},
1: {x: 736, y: 373.5},
2: {x: 736, y: 357.5},
3: {x: 720, y: 373.5},
4: {x: 736, y: 389.5},
6: {x: 720, y: 373.5},
7: {x: 752, y: 389.5},
8: {x: 704, y: 357.5},
9: {x: 752, y: 341.5},
10: {x: 720, y: 405.5},
11: {x: 704, y: 373.5},
]


setInterval循环中,我生成新坐标,并想检查这些坐标是否存在于我的对象中,以便重新生成它们,直到获得不存在的坐标为止。说:

var newPosition = [720, 389.5];
// return true
var newPosition = [720, 357.5];
// return true

最佳答案

您可以Array#some并检查属性。



const
    addTo = array => ([x, y]) => {
        if (positions.some(o => o.x === x && o.y === y)) return;
        array.push({ x, y });
    };

var positions = [{ x: 720, y: 389.5 }, { x: 736, y: 373.5 }, { x: 736, y: 357.5 }, { x: 720, y: 373.5 }, { x: 736, y: 389.5 }, { x: 720, y: 373.5 }, { x: 752, y: 389.5 }, { x: 704, y: 357.5 }, { x: 752, y: 341.5 }, { x: 720, y: 405.5 }, { x: 704, y: 373.5 }],
    add = addTo(positions);

add([720, 389.5]);
console.log(positions); // not added

add([720, 357.5]);
console.log(positions); // added

.as-console-wrapper { max-height: 100% !important; top: 0; }

09-20 18:28