2017-02-20 136 views
1

在數組集合中查找數組索引的最佳方法是什麼?爲什麼indexOf()返回正確的索引?我猜這是與對象平等有關嗎?使用indexOf獲取數組集合的索引(Javascript)

我見過其他解決方案循環收集並返回滿足等式檢查時達到的索引,但我仍然好奇爲什麼indexOf()不做同樣的事情。另外,由於IE 11的支持,我無法使用ES6的find/findIndex。我已經在下面包含了我的測試代碼。非常感謝。

var numbers = [ [1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12] ]; 
 

 
function getIndex (numbersToTest) { 
 
    return numbers.indexOf(numbersToTest); 
 
}; 
 

 
function test() { 
 
    console.log(getIndex([1, 2, 3, 4, 5, 6])); // Except 0 
 
    console.log(getIndex([7, 8, 9, 10, 11, 12])); // Expect 1 
 
    console.log(getIndex([2, 1, 3, 4, 5, 6])); // Expect -1 (not in same order) 
 
} 
 

 
test();

+0

你說得對,它與對象平等有關,因爲'[] == []'是'false'。 –

+0

我有這個問題的答案,在這種情況下可以util比較數組作爲字符串,https://jsfiddle.net/dbpLenwu/ –

+0

@trincot我不認爲這是一個重複的問題,因爲我一直在尋找最好的找到數組索引的方法,也想了解爲什麼indexOf不起作用(這不是主要討論點)的一些背景信息。非常感謝。 – poolts

回答

1

對象引用(包括數組引用)作爲參考值進行比較;一個對象引用只有在兩個引用都是完全相同的對象時才相等。比較不是基於數組的內容執行的,在你的情況下。即使傳入的數組具有相同的值,但它們是不同的數組,因此不等於原始列表中的任何數組。

相反,你需要使用類似Array#find(查找條目)或Array#findIndex(查找條目的指數),通過在數組中numbersnumbersToTest進行比較,看它們是否等同陣列回調。 This question's answers討論各種方式來有效地比較陣列的等價性。

例如:

var numbers = [ [1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12] ]; 
 

 
function getIndex (numbersToTest) { 
 
    return numbers.findIndex(function(entry) { 
 
    // Simple comparison that works for an array of numbers 
 
    return entry.length === numbersToTest.length && entry.every(function(number, index) { 
 
     return numbersToTest[index] === number; 
 
    }); 
 
    }); 
 
}; 
 

 
function test() { 
 
    console.log(getIndex([1, 2, 3, 4, 5, 6])); // Expect 0 
 
    console.log(getIndex([7, 8, 9, 10, 11, 12])); // Expect 1 
 
    console.log(getIndex([2, 1, 3, 4, 5, 6])); // Expect -1 (not in same order) 
 
} 
 

 
test();

注意兩個Array#findArray#findIndex是新生(ES2015,又名 「ES6」),但可以polyfilled爲老年人JavaScript引擎。

+0

謝謝@TJCrowder我欠你一杯啤酒:) – Pointy