我试图在 Javascript 中找到另一个数组中一个数组的索引,如下所示:
const piece = [5, 10];
const array = [[5, 10], [5, 11]];
//Using indexOf
console.log(array.indexOf(piece));
//Using findIndex
console.log(array.findIndex(function(element) {
return element == piece;
}));Run Code Online (Sandbox Code Playgroud)
我期望这些返回 0,因为这是我的“片段”在较大数组内的索引,但这两种方法都返回-1
有什么想法为什么会发生这种情况吗?如果我有其他方法可以做到这一点?
谢谢。
要比较实际值,您可以使用JSON.stringify()方法:
piece = [5, 10];
array = [[5, 10], [5, 11]];
//Using findIndex
console.log(array.findIndex(function(element) {
return JSON.stringify(element) == JSON.stringify(piece);
}));Run Code Online (Sandbox Code Playgroud)