JavaScript或jQuery是否具有类似于Excel的VLOOKUP的功能?

pyo*_*yon 6 javascript jquery

JavaScript或jQuery是否有一个函数返回一个数组的元素,该数组的索引等于另一个数组中给定值的位置?(我可以写自己的,但我不想重新发明轮子.)

就像是:

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

但是,嗯...在标准库中.

Bra*_*tie 6

也许这样的事情?

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;
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以对双数组使用它,就像这样

根据您的目的,您可以修改indexOf以使两个字符串首先小写,以便比较不会因"foo"与"FOO"而失败.另请注意,如果index超过行的长度,则返回整行(通过修改该: row);部分,可以轻松地将其更改为第一个元素(或其他).