如何检查x和y是否在对象中?

乙胺

我有一个包含一些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
妮娜·斯科茨(Nina Scholz)

您可以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; }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章