我有一个这样的坐标数组:
coordinates = [
{x: 1, y: 2},
{x: 3, y: 4},
{x: 5, y: 6},
{x: 7, y: 8},
{x: 9, y: 0}
];
我想在这个数组中查询这样的对象。
var searchFor = {x: 1, y: 2}
我试过这个:
if ($.inArray(searchFor, coordinates) !== -1) {
...
}
但这总是返回-1。我只需要有关对象是否在此数组中的真/假信息。我怎样才能做到这一点?
最佳答案
这是因为对象彼此不相等 - 即使它们具有相同的属性/值 - 除非它们是完全相同的实例。
您需要做的是手动遍历数组:
for( var i=0, l=coordinates.length, found = false; i<l; i++) {
if( coordinates[i].x == searchFor.x && coordinates[i].y == searchFor.y) {
found = true;
break;
}
}
if( found) {
// ...
}
关于javascript - 在 JavaScript 中查询对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17343053/