通过比较两个具有相同数字的数组,IndexOf 返回 false。
它也不适用于单个数字,例如位置[i].位置[j]。 我想比较整个数组,而不仅仅是单个整数。 [32, 33, 34] & [35, 34, 33] 也应该返回 true...有更好的方法吗?
(...)
//Array of ship locations
ships: [
{location:[13, 23, 33]},
{location:[2, 12, 22]},
{location:[15, 14, 16]},
{location:[17, 18, 19]},
{location:[31, 41, 51]},
{location:[40, 41, 42]}
],
//Array with additional ship location
position: [
{location: [2, 12, 22]},
{location: [40, 41, 42]}
],
collision: function(position) {
if(this.ships.length > 1) {
for(var i = 0; i < this.ships.length; i++) {
for(var j = 0; j < position.length; j++) {
if(this.ships[i].location.indexOf(this.position[j].location) >= 0) {
return true;
} else {
return false;
}
}
}
} else {
return false;
}
}
console.log(model.collision(model.position)); //returns false
最佳答案
由于称为“按值传递与按引用传递”的行为,.indexOf 方法不适用于 JavaScript 中的复杂对象,例如数组或对象文字。这是一个冗长的主题,涉及如何存储原始值(字符串、数字、 bool 值)与如何存储复杂值(对象)。
如果要比较两个数组是否“相同”(即两个数组是否包含相同的整数序列),则必须检查每个数组中的每个索引。
关于javascript - IndexOf 不适用于两个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56247984/