2011-03-02 155 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);部分,可以轻松地将其更改为第一个元素(或其他)

相关问题