2011-03-02 162 views
5

JavaScript或jQuery有一個函數返回一個數組的元素,該數組的索引等於另一個數組中給定值的位置? (我可以寫我自己,但我不想推倒重來。)JavaScript或jQuery是否具有與Excel VLOOKUP類似的功能?

喜歡的東西:

function vlookup(theElement, array1, array2) { 
    $.each(array1, function(index, element) { 
     if (element === theElement) 
      return array2[index]; 
    }); 
    return null; 
} 

但是,嗯......在標準庫。

+0

您的示例看起來不像[典型的vlookup用法](http://www.techonthenet.com/excel/formulas/vlookup.php),但是自己編寫代碼有什麼問題? – 2011-03-02 20:04:17

+0

我不喜歡編碼我可以編碼的東西,因爲我是個蠢貨白癡,我更喜歡使用實際設計/測試的標準庫。 – pyon 2011-03-02 21:15:32

回答

4

也許這樣的事情?

Array.prototype.vlookup = function(needle,index,exactmatch){ 
    index = index || 0; 
    exactmatch = exactmatch || false; 
    for (var i = 0; i < this.length; i++){ 
     var row = this[i]; 

     if ((exactmatch && row[0]===needle) || row[0].toLowerCase().indexOf(needle.toLowerCase()) !== -1) 
      return (index < row.length ? row[index] : row); 
    } 
    return null; 
} 

然後你可以用它對付雙陣列,like so

根據你的目的,你可以修改indexOf,使兩個字符串小寫第一所以比較不會與「富」與失敗「 FOO」。另請注意,如果index超過了行的長度,整行將被返回(通過修改: row);部分,可以輕鬆地將其更改爲第一個元素(或其他)

相關問題