[英]JavaScript - find index of array inside another array
我試圖在 Javascript 中的另一個數組中找到一個數組的索引,如下所示:
piece = [5, 10]; array = [[5, 10], [5, 11]]; //Using indexOf console.log(array.indexOf(piece)); //Using findIndex console.log(array.findIndex(function(element) { return element == piece; }));
我希望這些返回 0,因為這是我的“片段”在較大數組中的索引,但兩種方法都返回 -1。
任何想法為什么會發生這種情況? 如果我有其他方法可以做到這一點?
謝謝。
您正在比較各自創建的對象(數組),因此它們不是相同的對象。 如果需要,您可以比較 arrays 中的每個整數,當數組長度也匹配時,您可以得出結論它們是“相同的”:
piece = [5, 10]; array = [[5, 10], [5, 11]]; //Using findIndex console.log(array.findIndex(function(element) { return element.length === array.length && element.every((val, i) => val == piece[i]); }));
要比較實際值,您可以使用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); }));
JavaScript中的Arrays不是按值比較,而是按引用比較。 所以如果你有 arrays a 和 b 像這樣:
const a = [1, 2];
const b = [1, 2];
當您使用 == 或 === 比較它們時,會比較它們的引用,而不是值。 所以這個console.log(a == b)
或console.log(a === b)
將打印錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.